Page 1 of 1

Problem with Lua module

Posted: Thu May 01, 2014 11:56 pm
by scorpii
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.

What am I doing wrong here?

interface.lua

Code: Select all

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
main.lua

Code: Select all

local interface = require("interface")

function prim1Callback(msg)
	print(string.format("prim1Callback: %s", msg))
end

function love.load()
	interface.dispatch(1, "TEST")
end

Re: Problem with Lua module

Posted: Fri May 02, 2014 12:49 am
by SneakySnake
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.

Code: Select all

function prim1Callback(msg)
   print(string.format("prim1Callback: %s", msg))
end

local interface = require("interface")

function love.load()
   interface.dispatch(1, "TEST")
end


Re: Problem with Lua module

Posted: Fri May 02, 2014 8:08 am
by scorpii
Oh, yes of course! Thanks! :)
I'll just have an init function that the user of the interface must call first then.

Code: Select all

local callbacks = {}
function interface.init()
	callbacks = {
		prim1Callback,
		prim2Callback
	}
end