How to access tilemap instance in lua module (SOLVED)

I’m trying to use a lua module for procedural tilemap generation. I’m using parts of the random walker code that Britzl made.
The problem is I can’t figure out how to access the tilemap from the lua module.
I have a collection with a GO, a tilemap and a script. I create the collection from a collection proxy.
The defold script can access the tilemap by url ("#city"). But the lua module can’t.

Trying to do tilemap.get_bounds("#city") gives me an error:
attempt to call field 'get_bounds' (a nil value)
The same call works fine from the defold script.

How do I get the url or id to use from the lua module?

A simple function could be:

tilemap.lua

local M = {}
function M.get(map)
local x,y,w,h = tilemap.get_bounds("#city")
end
return M

and you call it from a script

local map = require  "tilemap"
function init(self)
map.get("#city")
end
1 Like

That’s what I am doing, and it throws the error.
I think the problem may be that the GO with the tilemap is created with collection proxy. From reading the Defold docs I’m starting to think that I should use the instance Id associated with the GO created by the proxy. But I can’t figure out how to get the Id.

you can then say

function init(self)
map.get("yourspawnedcollectionname:/gameobjectname#city")
end

No. The error means that the field get_bounds in the tilemap table is nil. That means that the runtime cannot find a function called tilemap.get_bounds().

Maybe you have overwritten or shadowed the tilemap global variable?

2 Likes

My spawn collection is the collection name? I thought the collections didn’t exist in runtime. Or is it the proxy?
I think I tried doing that already but I will check again.

Oh…

I have done that actually! My tilemap-id variable is called “tilemap”. :blush:
Not used to functions as first class objects!

2 Likes

Haha, that was the problem!
How embarrasing :smiley: :smiley:
Thanks!

Follow up question:
Are “tables” in lua similar to objects in js?

1 Like

No. Tables are associative arrays. There is no inheritance like with js objects. Tables can be used to store any value, including tables and functions. Functions stored in a table are like any other function. There is no automatic “self” or “this” like object methods. If you need that you have to pass it explicitly (there is the “:” syntactic sugar though).

2 Likes

Lua tables, functions as first class citizens and coroutines are the things that makes Lua absolutely awesome. It makes the language very powerful and certain things become very easy to implement.

3 Likes

Thanks for the explanation guys! :+1: