Problem with Lua module

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
User avatar
scorpii
Prole
Posts: 9
Joined: Tue Apr 22, 2014 9:29 pm
Location: Sweden

Problem with Lua module

Post 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
Löve noob
Lua noob
Life noob
User avatar
SneakySnake
Citizen
Posts: 94
Joined: Fri May 31, 2013 2:01 pm
Contact:

Re: Problem with Lua module

Post 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

User avatar
scorpii
Prole
Posts: 9
Joined: Tue Apr 22, 2014 9:29 pm
Location: Sweden

Re: Problem with Lua module

Post 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
Löve noob
Lua noob
Life noob
Post Reply

Who is online

Users browsing this forum: Google [Bot] and 3 guests