teal-language / tl

The compiler for Teal, a typed dialect of Lua
MIT License
2.15k stars 111 forks source link

Global functions #500

Closed lua-rocks closed 2 years ago

lua-rocks commented 2 years ago

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:

function test(...: number): number...
  return ...
end

... which defines global variable test without a global keyword.

hishamhm commented 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:

Would you be interested in making a PR to address whatever was confusing in the tutorial about this? Thank you!

Calandiel commented 2 years ago

Out of curiosity, why global by default for functions?

lua-rocks commented 2 years ago

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.

Calandiel commented 2 years ago

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.

lua-rocks commented 2 years ago

@Calandiel yes, I got you, I just expanded my thoughs. We are talking about the same thing :)

hishamhm commented 2 years ago

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!