2

I have the following test code:

local luatable = {}
luatable.item1 = 'abc'
luatable.item2 = 'def'

I'd like to know how to change it so that I can dynamically assign the names becuase I don't know how many "items" I have. I'd like to do something like this: (pseudo code)

n = #someothertable
local luatable = {}

for i = 1, n do
  luatable.item..i = some value...
end

Is there a way to do this?

2 Answers 2

5

I'd like to do something like this: luatable.item..i = value

That would be

luatable['item'..i] = value

Because table.name is a special case shorthand for the more general indexing syntax table['name'].

However, you should be aware that Lua table indexes can be of any type, including numbers, so in your situation you most likely just want:

luatable[i] = value
Sign up to request clarification or add additional context in comments.

Comments

1

Yes, and the correct code is

for i = 1, n do
  luatable["item"..i] = some value...
end

Recall that luatable.item1 is just sugar for luatable["item1"].

Comments

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.