lua-users home
lua-l archive

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




- basic modules and functions won't be modified, or at least not in a way that alters their semantics. With this I can rely on documented behavior to precompile functions calls, like compiling string.rep("a", 3) directly to "aaa". This might appear with some frequency when function calls are inlined.

If you want to eval functions at compile-time, you can do it with metalua. The level-0 block below allows to eval %-prefixed expressions at compile time. Therefore, "%string.rep('a', 5)" compiles straight to "`String 'aaaaa'", as one might expect.

-{ block:

   -- Compile and eval an aexpression AST, then quote the result
   function cteval_builder(x)
      -- Compile and execute the AST at compile-time:
      x = mlc.function_of_ast{`Return{x[1]}}()
      -- Quote back the evaluated result:
      return mlp.x_quote(x)
   end

   -- syntax extension
   mlp.expr:add { "%", mlp.expr, builder = cteval_builder } }

-- Usage sample:
x = %string.rep('a', 5)


With a code walker, you can easily locate side-effect free functions known at compile time, and when their arguments are closed, evaluate them at compile time with a function very similar to cteval_builder().