Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
3

Is it possible to make a public variable?

Asked by
Kyokamii 133
9 years ago

I know that in C# you can use public variables that other scripts can use, but can you do the same in lua?

1 answer

Log in to vote
1
Answered by
Necrorave 560 Moderation Voter
9 years ago

You have two options regarding what you are looking for.

First would be whats we call Global Variables. You can declare a global variable by placing _G. before the name of the variable. You will be able to call this variable from almost any script within your game file.

Script 1:

_G.bool = true -- Creates a global variable and assigns 'true' as the value

Script2:

print (_G.bool) --Should print 'true'

Another option would be to create a Module Script with variables you wish to use in multiple scripts. These work somewhat similar to global variables when you refer to them in other scripts.

Lets say you made a module script returned the array of variables called _M. After you pull the module script into your new script, you can refer to the variables as _M.variable or whatever you named the variable you created in the module script.

Example of module script:

_M = {
    bool = true
}

return _M

How to call the variable in the module script:

_M = require('Path to Module Script') -- This will call the module script and return the variables

print (_M.bool) --This should print 'true'

Let me know if this answers your question.

0
It does answer my question! Kyokamii 133 — 9y
0
Glad to help! Necrorave 560 — 9y
1
Note that global variables in Lua are poor style for the same reason that public variables are poor style in C#. BlueTaslem 18071 — 9y
Ad

Answer this question