Lua Notes

include files
Login

implementing #include

Lua can read a file, parse the file, and then inject it directly into your Nelua. The parsing step is necessary because 'your Nelua' that is calling include has already been parsed, and simple string fragments can't be added anymore.

-- hw.nelua
print('hello, ' .. target)

-- ex.nelua
##[[
local function include(path)
  local body, err = fs.readfile(path)
  if not body then assert(false, err) end
  local ast = aster.parse(body, path)
  inject_astnode(ast)
end
]]

require 'string'
local target = 'world'
## include 'hw.nelua'
## include 'hw.nelua'

Output:

hello, world
hello, world

This demonstrates that multiple includes work just fine, and that hw.nelua can see ex.nelua's local variables, but the reverse isn't true: local variables can't be defined in hw.nelua for ex.nelua to see, probably as the included code is treated as contained in its own block. As a workaround for that (and maybe as the better thing to do anyway), an existing namespace can be modified:

-- hw.nelua
function M.greet() print('hello, ' .. target) end

-- ex.nelua
##[[
local function include(path)
  local body, err = fs.readfile(path)
  if not body then assert(false, err) end
  local ast = aster.parse(body, path)
  inject_astnode(ast)
end
]]

require 'string'
local target = 'world'
local M = @record{}
## include 'hw.nelua'
M.greet()