What is the difference between the following Lua scripts in terms of function scope. How would it effect the need to require 'calculator' in some other Lua script. And how would it be referenced in say a LuaState.getGlobal(function_name). What would be its proper function name? Also any comment on advantages/disadvantages of the declaration approaches.
A) Calculator.lua
function foo(n)
return n+1;
end
B) Calculator.lua
calc= {}
function calc.foo(n)
return n+1;
end
C) Calculator.lua
function foo(n)
return n+1;
end
function calculator()
calc = {}
calc.foo=foo
return calc
end
I don’t know what it is you mean exactly by the “scope” of these scripts. Exactly what these scripts do depends on how they’re being executed. You could give them a different environment, thus changing what they think of as “globals”.
So, I will explain what each of these scripts does based on the assumption that you are loading them with
dofile,dostring, or something of the like. That is, you’re applying them to the global environment.A)
This creates a single global variable,
foo, which is a function.B)
This creates a single global variable,
calc, which is a table. This table has a single entry, with the keyfoo, who’s value is a function.C)
This creates two global variables.
foois a function.calculatoris also a function. Each call tocalculatorwill cause the global variablecalcto be overwritten. The new value ofcalcwill be a table that has a single entry, with the keyfoo, who’s value is a copy of what is stored in the global variablefoo.It’s hard to say what the “advantages” of method C are, since it makes no sense. It creates two functions instead of one, and that second function keeps creating new tables.
B is just a “namespace” scoped version of A. The general expectation with Lua modules is that including them will usually create some table that will contain all of the functions in that module, to avoid name conflicts with existing global state. In that regard, B may be better. But it depends mostly on what this script will be used for.
Personally, for simple shell scripts and utility scripts, I don’t bother with proper module scoping. When I do make a proper module, I generally use the
moduleLua function.