It helps if you write every table modification inside of a new function. This way you keep your code more readable.
The following examples are re-written code. You could use this as a start, but make sure to test it, because I didn't test it for you.
local farm = createFarm(123, 1, 1, 1)
local horse = createHorse(player, horseId)
local farm = getFarmFromID (123)
-- If the farm does exist
if farm then
addHorseToFarm(horse, farm)
end
local horseCollection = {} -- all horses
local farmCollection = {} -- all farms
---@param player userdata
---@param horseId integer
---@return table
function createHorse(player, horseId)
local horse = { id = horseId }
horseCollection[horseId] = horse
return horse
end
---@param farmId integer
---@param x number
---@param y number
---@param z number
---@return table
function createFarm (farmId, x, y, z)
local marker = createMarker(x, y, z)
local farm = {
marker = marker,
id = farmId,
location = { x, y, z },
owner = nil,
creator = nil,
creationTime = getTickCount(),
price = 0,
horses = {}
}
farmCollection[farmId] = farm
return farm
end
---@param farmId integer
---@return table|false
function getFarmFromID (farmId)
return farmCollection[farmId] or false
end
---@param farm table
---@param player userdata
---@return table
function setFarmCreator (farm, player)
farm.creator = player
return farm
end
---@param horse table
---@param farm table
function addHorseToFarm (horse, farm)
table.insert(farm, horse)
end
---@param horse table
---@param farm table
---@return boolean
function isHorseInFarm(horse, farm)
for i=1, #farm do
if farm[i] == horse then return true end
end
return false
end
---@param farmId integer
---@return boolean
function doesFarmExist(farmId)
return farmCollection[farmId] and true or false
end