2

Why does this syntax work:

if ({A=1,B=1,C=1})["A"]  then print("hello") end

while this does not:

local m = {string.sub(string.gsub("A,B,C,", ",", "=1,"),1,-2)}

if (m)["A"]  then print("hello") end

???

I think it's because a string is not an array, but how can I convert a string ("a,b,c") to an array ({a=1,b=1,c=1})?

2
  • 4
    Please do not vandalize your posts. By posting on the Stack Exchange network, you've granted a non-revocable right for SE to distribute that content (under the CC BY-SA 3.0 license). By SE policy, any vandalism will be reverted. If you would like to disassociate this post from your account, see What is the proper route for a disassociation request? Commented Aug 11, 2017 at 11:22
  • As has already been mentioned, you are not allowed to vandalize your old questions by replacing them with nonsense. You are also not allowed to completely change your question if doing so will invalidate existing answers. Since you would not stop doing this, this question has been locked to prevent further edits. Commented Aug 11, 2017 at 11:38

1 Answer 1

5

This line

local m = {string.sub(string.gsub("A,B,C,", ",", "=1,"),1,-2)}

is equivalent to this

local v = string.sub(string.gsub("A,B,C,", ",", "=1,"),1,-2)
local m = {v}

which, I hope you agree, would clearly not have the behavior of assigning multiple values in the m table.

To "parse" simple a=1,b=1,c=1 type strings into a table the second example of string.gmatch from the manual is helpful:

The next example collects all pairs key=value from the given string into a table:

t = {}
s = "from=world, to=Lua"
for k, v in string.gmatch(s, "(%w+)=(%w+)") do
  t[k] = v
end
Sign up to request clarification or add additional context in comments.

2 Comments

Note: the two samples are not equivalent in general; the second one truncates the result of string.sub to one value, while the first sample will store all return values in the array.
@ColonelThirtyTwo While true string.sub only ever returns one value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.