Local variable in function

On second thought this is more intricate than I first realized. The following example illustrates the problem:

local url1 = msg.url("test")

function init(self)
	local url2 = msg.url("test")
	print(url1)
	print(url2)
end
--> DEBUG:SCRIPT: url: [:test]
--> DEBUG:SCRIPT: url: [default:/test]

If you are using msg.url() in the top level context the engine cannot infer the socket (since it runs outside of the lifecycle functions of the script component). You end up with a faulty url object. There are two ways to fix this:

  1. Specify the socket in the urls (local url1 = msg.url("default:/test")). Using a relative address is generally a better idea so I would advice against this.
  2. Use hash paths instead of complete urls:
local IDS = {}

IDS.colorwheel = hash("colorwheel")
IDS.spinner = hash("spinner")

return IDS

(Edit: the reason for using relative paths is that it allows you to build objects with script that will work regardless of where in the collection hierarchy you place the objects)

3 Likes