call_delay / namespace problem?

This is probably a Lua issue (Lua is new to me). I have a module of shared functions.

In the test window I issue the following code:

require(“shared”)

shared.TestCallDelay() – see below

The above code results in a log entry : attempt to call global ‘switch_on’ (a nil value)

I imagine that my functions are not in the global namespace? If this is the problem, how do I get them there?

– sharedmodule

module(…, package.seeall)

function TestCallDelay()

local device  = 16

luup.call_delay( 'switch_on', 10) -- Call the switch on function after a delay of 2 seconds

luup.call_delay( 'switch_off', 20) -- Call the switch off function after a delay of 2 seconds


luup.call_delay( 'switch_on', 30) -- Call the switch on function after a delay of 2 seconds

luup.call_delay( 'switch_off', 40) -- Call the switch off function after a delay of 2 seconds


function switch_on()
   luup.call_action("urn:upnp-org:serviceId:SwitchPower1","SetTarget",{ newTargetValue="1" },device)
end

function switch_off()
   luup.call_action("urn:upnp-org:serviceId:SwitchPower1","SetTarget",{ newTargetValue="0" },device)
end

end

You are correct that your functions are not in the global namespace. They are lexically scoped within the TestCallDelay function. If you moved your device variable out of the TestCallDelay function or passed it as an argument to switch_on/off (as a stringified third argument to call_delay), and moved the switch_on/off out of the TestCallDelay function, then the functions (or rather, the variables which point to the functions) ought to appear in the global namespace.

I have moved the on / off functions outside TestCallDelay into the surrounding shared.lua but it looks like, using the require(“shared”) facility, the functions are in a context of the shared module as the same problem occurs. I guess the approach I need to take is to declare the delay functions in a device file but use an include file to get some code sharing.

In your init code
local function switch_on()

end
local function switch_off()

end

function init()
_G[“switch_on”] = switch_on
_G[“switch_off”] = switch_off
end

Mucking with _G gets messy, esp if multiple libs start doing it. I don’t know if I’d recommend that… At least not without providing control over the names used (to avoid naming collisions down the line)

I agree about naming convention … I always make my global functions have a module prefix to minimize the chance of a collision …

But LUUP assumes the functions are in the Global Table … They should have
an option to pass the function reference instead of the name.

It’s cleaner to keep these calls encapsulated in the LUA code then to move then to XML so that they end up in the global name space. Even their … they still have the possibility to override a global function.