Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LUA Variables as Table Keys

Tags:

lua

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?

like image 771
Teknetik Avatar asked Sep 16 '26 01:09

Teknetik


1 Answers

{ [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.

like image 59
mlepage Avatar answered Sep 18 '26 19:09

mlepage



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!