teal-language / tl

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

Allow predeclaration of local functions #567

Closed catwell closed 1 year ago

catwell commented 1 year ago

Consider this code sample:

local foo : function()
function foo() end
foo()

Before this change it would fail with:

========================================
1 error:
invalid.tl:2:1: functions need an explicit 'local' or 'global' annotation

This change makes it valid again (it was the case before 0.14).

Rationale: in Lua function foo() end is sugar for foo = function() end, and I suppose it should remain the same in Teal.

This kind of code is useful to write mutually recursive functions such as this:

local collatz_odd : function(integer): integer

local function collatz_even(n: integer): integer
    print(n)
    n = n // 2
    if n % 2 == 1 then
        return collatz_odd(n)
    end
    return collatz_even(n)
end

function collatz_odd(n: integer): integer
    print(n)
    if n == 1 then
        return 1
    end
    return collatz_even(3 * n + 1)
end

collatz_odd(7)
github-actions[bot] commented 1 year ago

Teal Playground URL: https://567--teal-playground-preview.netlify.app

hishamhm commented 1 year ago

I had no strong feelings myself about supporting or not this Lua idiom, but I suppose it is consistent and unambiguous enough, and given the finished PR, I'm happy to merge it :)