Jump to content

Splitting up String Variables


Recommended Posts

I am trying to create save/load game function in my RPG Wherigo that will save and load EXP, Gold, and items the player carries. Is it possible to split up a 6 letter string variable so that each Letter is displayed as a separate variable?


 For example, I have Var A = WXEFOQ. Is it possible to split this up into 6 variables? I.e. Var1 = W, Var2 = X, Var3 = E, Var4 = F, Var5 = O, Var6 = Q


I am trying to create a series of If/else statements that will read each letter and call back how much gold, exp, and items the player carries.  

Link to comment

Assuming your string is exactly six letter long;


local s = "WXEFOQ";

local c1 = string.sub(s, 1, 1); -- c1 = "W"
local c2 = string.sub(s, 2, 2); -- c2 = "X"
local c3 = string.sub(s, 3, 3); -- c3 = "E"
local c4 = string.sub(s, 4, 4); -- c1 = "F"
local c5 = string.sub(s, 5, 5); -- c2 = "O"
local c6 = string.sub(s, 6, 6); -- c3 = "Q"


However, this requires a whole bunch of additional variables. A more "general" solution might be to explode the string to a table (aka array)...


function explode(s)
    local characters = {}
    for i = 1, #s do
        characters[i] = string.sub(s, i, i)
    return characters

local characters = explode("WXEFOQ") -- { 1 = "W", 2 = "X", 3 = "E" ... }


...and then to access table elements in your conditions...


if (characters[1] == "W") then ... end
if (characters[2] == "X") then ... end
-- and so on.


Edited by Hügh
  • Helpful 1
Link to comment

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...