Closed lua-rocks closed 2 years ago
It's an issue of wording in the tutorial: you cannot make an assignment to an undeclared global — unlike Lua, an assignment does not make a global pop into existance. You need to declare the global in some way:
global
keywordglobal function
to declare global functionsfunction
(which means the same as global function
); the function
statement counts as a declaration.Would you be interested in making a PR to address whatever was confusing in the tutorial about this? Thank you!
Out of curiosity, why global by default for functions?
Functions occupy the same space in the global scope as any other types.
Local variables will be available only in current file and will be automatically deleted by the garbage collector if not used anywhere:
local foo = "bar"
local function sum(x,y)
return x + y
end
Global variables will be available everywhere in your project and may create name conflicts; the garbage collector won't touch them:
hello = "world"
function say(s)
print(s)
end
_G.say(_G.hello) -- world
Use luacheck to find all global and unused variables in your code.
In a perfect world, no variables should be global. Especially by default.
I believe you misunderstood me. I know how it works, I'm asking for the reasoning behind making functions global by default in teal specifically. The language design decision.
@Calandiel yes, I got you, I just expanded my thoughs. We are talking about the same thing :)
I believe you misunderstood me. I know how it works, I'm asking for the reasoning behind making functions global by default in teal specifically. The language design decision.
The original language design decision of accepting a bare function
as a global function declaration was simply to keep the Lua behavior since that did not seem to present an ambiguity for Teal: a bare assignment of an unknown variable was more immediately obvious as an error in a typed language, where as a function declaration presents a clearer intent of, well, declaration. Note that the same is true of type
, record
and enum
.
But we could just just as well reject bare functions and require that either global
or local
are used, in alignment with how variable declarations and type declarations work. I'm curious about what the Teal community thinks about this, I'll post this question on our Matrix chat!
Tutorial says that one does not simply define a global variable without the
global
keyword and then it shows the example of such a function:... which defines global variable
test
without aglobal
keyword.