Returning table with variable

Hi. I want to know how to declare a variable whithin the table instead of function.
Example:

local t = {}

t.work = function()

end

return t

how to do that but instead of “t” is a function, “t” is just a variable.

I have tried this:

t = {}

t.work = {}

t.image = display.newImageRect("some image.png, 50, 50)

table.insert(t.work, t.image)

return t

but when I reload this as module for the second time, t.work seems became a nil value. Please help me.

I’m really not sure what you your plans are for the display object with that table.insert, but that’s completely unnecessary.

Your issue is probably due to your t being a global, so you may rewrite it at some point. All modules should rely on local variables to avoid issues like that. When you first require the module, t is created, but if you re-require the module elsewhere after you’ve rewritten t, then Lua just accesses the existing module instead of recreating it.

Always stick to locals if you are uncertain.

‘Sorry, I just forgot to indicate local firs for this example’.
I have tried this:

local t = {}

t.work = {}

t.image = display.newImageRect("some image.png, 50, 50)

table.insert(t.work, t.image)

return t

but when I reload this as module for the second time, t.work seems became a nil value. Please help me.

The code that you’ve provided, as long as you have that image and the display object gets created, won’t have any issues unless you manually make changes to it at some point.

The only way for t.work to become nil is if you explicitly make it nil somewhere. If instead you are referring to the display object being nil, then it may happen because you insert it to some scene group, which gets cleared up somewhere, etc.

Anyway, with the code you’ve provided, there’s no way for t.work to ever become nil unless you explicitly make it so.


If you continue to have issues with this, then please upload a small project that demonstrates your issue so that others can see what is going on.

Thank you very much. It happened because I tried to reload the scene where I’m already in. The lesson is to never go to scene you’re already are. “Dont go to sceneA from sceneA.”

The real lesson is to never create display objects like that.

1 Like

Yes, Thank you very much, now I am enlightened.