This does not affect the performance in any noticable way at all. Local variables in Lua are really, really quick. While you don’t necessarily need it, and while readability is not really improved nor made worse in my eyes, at least, it is completely up to you. If you can read the code faster with it - go ahead.
The strings are hashed by the engine. I assume every frame though so if you pre-hash it’s faster. (What is the actual source of the builtin hash function?)
You can use a hash instead of a string, and then hash your strings once to get their hashes.
There is a cost associated with creating new url objects, and a slight difference if you reuse hashes. In tight loops this may matter. On my machine i get the following results on 1 million iterations. The difference may be bigger or smaller on a handheld.
for i=1,1000000 do
test(msg.url("hello"))
end
-- 0.78450298309326 seconds
local h = hash("/hello")
for i=1,1000000 do
test(msg.url(h))
end
-- 0.61077499389648 seconds
local url = msg.url("hello")
for i=1,1000000 do
test(url)
end
-- 0.10395789146423 seconds
You can make a Lua module and list all of your urls there if you would like. AURL does this kind of thing automatically for you. A manual version would look like
urlmodule.lua
local M = {}
M.my_url = msg.url("my_url")
return M
A script using urlmodule.lua
local urls = require("urlmodule")
print(urls.my_url)
go.set() and go.get() can’t be used to reference components in other “root” collections, or game worlds. That is, collections that has been loaded via proxy. To communicate between collections loaded by proxy, use message passing.
The error message is unclear. Any suggestions for how to make it better?
I just copied the error log message directly from the console. I just want to reuse the urls that I have created previously instead of creating new ones everytime.
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:
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.
(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)