Hi guys,
I have a very basic Lua problem I guess. I've been trying to implement a simple module as a basic messaging interface with a couple of primitives, static callback functions and a dispatcher function. The problem is that when I try to use the callbacks array it always results in nil.
I've attached my simple test. I expected that the string "TEST" would be printed to the console. That doesn't happen. Instead I get the "primitive not implemented" printout. Obviously "callbacks[1]" returns nil. It works as expected if I have the same code directly in the main.lua file.
local interface = {}
local callbacks = {prim1Callback}
function interface.dispatch(prim, msg)
if callbacks[prim] then
callbacks[prim](msg)
else
print(string.format("dispatch: primitive not implemented: %d", prim))
end
end
return interface
local interface = require("interface")
function prim1Callback(msg)
print(string.format("prim1Callback: %s", msg))
end
function love.load()
interface.dispatch(1, "TEST")
end
It's the order of execution.
When you require "interface", the execution of main.lua pauses, and interface.lua gets executed. prim1Callback doesn't exist yet when interface.lua is executing.
You can just put the function definition before you require interface.lua.
function prim1Callback(msg)
print(string.format("prim1Callback: %s", msg))
end
local interface = require("interface")
function love.load()
interface.dispatch(1, "TEST")
end