Teknetik
Teknetik

Reputation: 178

LUA Variables as Table Keys

I create and populate a table:

table.insert(logTable, { [probeName] = "log text" }

Is that the correct way to use a variable in the [key] section?

I am thinking lua is interprating this as an integer rather than a string?

Upvotes: 3

Views: 10159

Answers (2)

mlepage
mlepage

Reputation: 2472

{ [probeName] = "log text" } will create a literal table indexed by the value of variable probeName. So it will depend on that value's type. It could be an integer, or a string, or a function or table etc.

So:

probeName = 'abc'
for k, v in pairs({ [probeName] = "log text" }) do print(type(k), k, v) end
probeName = 123
for k, v in pairs({ [probeName] = "log text" }) do print(type(k), k, v) end
probeName = { 'another table' }
for k, v in pairs({ [probeName] = "log text" }) do print(type(k), k, v) end

Produces output:

string  abc log text
number  123 log text
table   table: 0xfa6050 log text

Now, table.insert(logTable, { [probeName] = "log text" } will actually take that literal table and insert it into another table (logTable) with integer index. So logTable will contain a bunch of integer-indexed table entries, which each have a single value (log text) which is keyed by some value (probeName). Iterate over it with ipairs. If rather you wished to accumulate all the logs by probe name into one table, you need to do something like logTable[probeName] = "log text" which is actually simpler. Iterate over it with pairs.

Hope this helps.

Upvotes: 5

Ilmo Euro
Ilmo Euro

Reputation: 5165

If probeName is a number, Lua will interpret it as such, but it won't convert a string containing digits to a number. If it is a number and you want to convert it to a string, you can use coercion (["" .. probeName]) or string formatting ([string.format("%d", probeName)]).

Upvotes: 1

Related Questions