First post here, very new to lua and basically any scripting language, so please if I have gone into too many details or let out the important ones, let me know.
What I’m basically trying to do, is have one separate .lua script in order to initialize tables or variables I need in my main.lua file.
The script, called initFunctions.lua
publicReturn = { ... } function publicReturn.initPlayer(lives) local player = { \_lives } player.\_lives = lives publicReturn = player print("init player ok!") end return publicReturn
is called in main.lua
local init = require("Scripts.initFunctions") local player = init.initPlayer(5) print("lives: " .. tostring(player.\_lives))
gives an error at the print() line, telling me I’m trying to index the local “player” which is a nil value.
What gives? Some other implementations do, work, such as returning the table inside the function, instead of at the end of the script
But that doesn’t make any sense to me, since the publicReturn should return the same value?
publicReturn = {} --\<---- just need to define an empty table function publicReturn.initPlayer(lives) local player = {} player.\_lives = lives print("init player ok!") return player end return publicReturn
What @rob is showing is a common Lua module pattern, so you do need to “return” the table to require it in another file.
Additionally, the “initPlayer” method is basically an initialization method added to the returned module, which is how you would add your custom values to the table.
You could also write it like so if you didn’t want the extra table object:
publicReturn = {} --\<---- just need to define an empty table function publicReturn.initPlayer(lives) local player = {} player.\_lives = lives print("init player ok!") return player end return publicReturn
What @rob is showing is a common Lua module pattern, so you do need to “return” the table to require it in another file.
Additionally, the “initPlayer” method is basically an initialization method added to the returned module, which is how you would add your custom values to the table.
You could also write it like so if you didn’t want the extra table object: