Page 1 of 1

Sharing vars around .lua files

Posted: Fri Nov 21, 2014 9:30 pm
by vitto
I would ask this question to be sure I'm not doing a best practice on how I should share a specific information around game lua files.

For example, I would share the game name "Super Generic Adventure" around my code for various reasons, for example the window title, or the name of the folder with the save games inside.

I didn't started seriously to code with lua, but reading examples around make me think I should share these data with functions so something like this:

Code: Select all

-- File A
function getGameName()
    return "Super Generic Adventure"
end

-- File B
function saveGameFile()
    local gameName = getGameName()
    -- do code to save game
end

-- File C
function setWindow()
    local gameName = getGameName()
    -- do code to set window size and title
end
I never programmed a video game and I never worked with lua, but I'm pretty sure it's easy to became crazy on organize it's code if it isn't organized as it should be, so is that a good practice or does exist better ways to do that?

I've noticed lua supports classes, so I suppose this is a must for who would write a well organized video game.

Re: Sharing vars around .lua files

Posted: Sat Nov 22, 2014 3:57 am
by Azhukar
There is no way you should organize, it's up to you what fits you best. Calling functions to request hardcoded variables is redundant.

For simple data like game name, settings or key bindings you can use a separate file with 1 global table containing all the variables. This is achieved by simply declaring the global table inside the file and including it before all other files that use the global table, which you can name "gameoptions" or some such. Then you can go and index gameoptions.gamename for example. All variables without the "local" at declaration are global.

Lua is case sensitive.

Re: Sharing vars around .lua files

Posted: Sun Nov 23, 2014 10:25 pm
by SiENcE