LUA functions returning nil when not expected

americanslon

Chieftain
Joined
Apr 3, 2019
Messages
14
Some code

local player = Players[playerId];
local unit = player:GetUnits():FindID(unitId);
local plot = Map:GetPlot(unit:GetX(), unit:GetY());
local city = Cities:GetCityInPlot(unit:GetX(), unit:GetY());

This code gets triggered OnUnitSelectionChanged. The unit is currently at a city but no matter what city related function I try the city is never detected.
I tried plot:isCity as well.

The code is in a file that is loaded as AddUserInterfaces with Context set as InGame (on a related note how many contexts are there and what are they?)

This is my first mod so forgive me if I am not even asking the question correctly.

Thank you!
 
I don't have an ability to try this for a couple of hours but i just wanted to point out that map:getplot works. It gets the plot. Is there a difference between .getplot and :getplot? Are they both supposed to work but return different things?
 
Map and Cities are plain global tables. The correct way to call functions from tables is via ".". You use ":" for "objects" which are tables but their functions are stored in the metatable.
Cities:GetCityInPlot returns nil. Cities.GetCityInPlot returns a proper plot.
Maybe devs did attach a metatable to Map pointing to itself, thus Map:function could also work, but this just a coincidence.
 
It seems that was it. Thank you!

Just to confirm, all the top levels (plot, player, players, cities, etc.) are tables and should be used with a ".", once the object is retrieved with a "." ":" is used to access object's methods correct?
 
Not exactly.

"Players" is a table, then you access Players[0] and get an object, so then you use Players[0]:function()
Plot is always an object, Map is a table.
Cities is table, single city is always an object.
Etc.
 
Top Bottom