lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


The simplest solution seems to be just declaring a non-const function
and then a const function that shadows it:

local function factorial(a, n)
  if n <= 0 then
    return a
  else
    return factorial(a * n, n - 1)
  end
end

local factorial<const> = factorial

print(factorial(1, 10))

It would be cool if the same sort of thing were achievable with

local function factorial<const>(a, n)
  if n <= 0 then
    return a
  else
    return factorial(a * n, n - 1)
  end
end

or if Lua could detect that a <const> variable is assigned to exactly
once in any execution path below its declaration. Rust does that for
variables declared with "let", but its compiler is probably thousands
or millions of times more complicated than Lua's.

let x;
if true { x = 10 } else { x = 20 }; // very un-idiomatic, but compiles at least
// x = 100 // error here if this is uncommented

— Gabriel