PhilipRoman/optic-lua-dev

Local recursive functions are declared as local AFTER expression evaluation

PhilipRoman opened this issue · 1 comments

Test case:

local function fact(n)
  if(n <= 1) then 
    return 1 
  else 
    return n * fact(n-1) 
  end
end

Will currently throw an error because inside the function body, "fact" is considered global.
Note that the next example must NOT work the same way, due to Lua language rules:

local fact = function(n)
  if(n <= 1) then 
    return 1 
  else 
    return n * fact(n-1) 
  end
end

The local x = function() ... end and local function x() ... end are NOT semantically equal - the second notation declares "x" BEFORE evaluating function body!

Apparently, this issue is impossible to fix in the compiler because the parser generates the same AST for both cases:

local function f() end
CHUNK
|  LOCAL_ASSIGNMENT
|  |  NAME_LIST
|  |  |  f
|  |  EXPR_LIST
|  |  |  FUNCTION
|  |  |  |  PARAM_LIST
|  |  |  |  CHUNK
local f = function() end
CHUNK
|  LOCAL_ASSIGNMENT
|  |  NAME_LIST
|  |  |  f
|  |  EXPR_LIST
|  |  |  FUNCTION
|  |  |  |  PARAM_LIST
|  |  |  |  CHUNK