Reputation: 749
I am trying to load a table into C++ from Lua. This is how the file looks:
function alma(arg)
print(arg)
end
sometable = {
num = 5,
text = "this is a string",
nested = {
{"a", alma("argument")},
{"table", alma("arg")},
{"element", alma("asd")}
}
}
If I call luaL_loadfile
I only get the chunk. If I call lua_dofile
I get the elements, but the alma function runs for each element. In this SO thread, someone said to wrap these kinds of stuff into functions and call that to get the data. When i wrap/call the function the 3 alma functions run the moment i call the getter. How can i get sometable
and its elements without executing the alma function?
Upvotes: 1
Views: 887
Reputation: 5902
and I'd like to have onClick events for gui elements, which would be some functions, hence the {"some string", function} table elements
Ok, you need function called later. Just save value of that functiion, i.e. simply write its name:
nested = {
{"a", func_argument},
{"table", func_arg},
{"element", func_asd}
}
But you want to call same function, passing arguments. And you want that info saved as a function. So either define a function directly in the table, or call some function that will return another function, storing its args in a closure:
-- function to be called
function alma(arg)
print(arg)
end
-- define functions in table
nested1 = {
{"a", function() alma "argument" end},
{"table", function() alma "arg" end},
{"element", function() alma "asd" end}
}
-- or create function within another function
function alma_cb(name)
return function() alma(name) end
end
nested2 = {
{"a", alma_cb "argument"},
{"table", alma_cb "arg"},
{"element", alma_cb "asd"}
}
Upvotes: 2
Reputation: 5902
You can't get any value without calling some function. Any chunk loaded is a function. Not the data, but function that will construct/return data. You must call it, so it will fill some global variables, or explicitly return values.
If you don't want alma()
called, then don't call it. Fill your table without calling alma()
.
For example:
return {
num = 5,
text = "this is a string",
nested = {
{"a", "argument"},
{"table", "arg"},
{"element", "asd"}
}
}
You must load and call this chunk, it will construct and return table with .nested
subtable, and alma()
won't be called.
Upvotes: 1