Reputation: 6998
I have some text and I'm trying to load it via load string. The following works:
local m = loadstring("data = 5")()
But when the data is a table it doesn't work and gives the error "attempt to call a nil"
local m = loadstring("data = { 1 = 10}")()
Upvotes: 0
Views: 1429
Reputation: 1171
If you had added an assert
you would have got a more helpful message:
local m = assert (loadstring("data = { 1 = 10}"))()
Result:
stdin:1: [string "data = { 1 = 10}"]:1: '}' expected near '='
stack traceback:
[C]: in function 'assert'
stdin:1: in main chunk
[C]: ?
And to actually answer the question, unless the table key happens to follow Lua variable naming rules, you have to put it inside square brackets, eg.
local m = assert (loadstring("data = { [1] = 10}"))()
m is still nil when I do this
What does that matter? The loadstring
is done.
Just do this:
assert (loadstring("data = { 1 = 10}"))()
print (data [1])
You don't need the variable m
. The loadstring
puts a table into data
- that is the important thing.
Upvotes: -1
Reputation: 80649
The table declaration in lua require integer keys to be put inside square brackets:
data = {
[1] = value,
}
The enclosing of keys in square brackets is always allowed, valid and possible. It can be skipped iff your key follows the pattern: [A-Za-z_][A-Za-z0-9_]*
(which is the same as a valid variable name in lua)
Upvotes: 2