r/lua • u/radstronomical • Jun 05 '25
Catch output from function called via load(string)
Hey there,
I'm coming back to lua after some time away... I'm trying to call a constructor based on a string from some Tiled output. I've had success doing this using the load function - the constructor is being called - but I can't seem to get a reference to the object created. Here's some example code:
function AddElement(_type, _x, _y)
if (_type == null) then return end
local s = _type .. "(" .. tostring(_x) .. "," .. tostring(_y) .. ")"
local makeElement = load(s)
local e = makeElement()
table.insert(elements, 1, e)
print(#elements)
endI am seeing output from print statements inside the elements' constructors, but the elements table is not increasing in size, and e seems to be nil. Any ideas?
2
Upvotes
3
u/hawhill Jun 05 '25
You just need to prefix your Lua string you’re feeding to load() with “return “.
That said your overall approach is, errrm, wild, but then you didn’t ask about that.
1
u/[deleted] Jun 05 '25 edited Jun 05 '25
load uses the global environment.
It's also a bad idea to use load that much, you should use it as few times as possible.
Can't you use listOfFunctions_type?
I would be careful of inserting nils and sparse lists are not traversable via ipairs, you must now (by hand) take into account the length of the table, if e then table.insert( ...
1
u/collectgarbage Jun 06 '25
To help you debug, put a call to assert() around the call to load(); and another around the call to makeElement()