Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Preventing a table iteration from reading a function value?

Asked by
ausmel105 140
7 years ago

Hello,

I'm trying to include methods with the following tables, the data won't change ingame so I don't need to use classes. I have included the following data structure as an example.

When I try and attach a method to a table within "airport.airlines.Airline", such as :GetDestinations() I get an error "attempt to index local 'v' (a function value)".

My guess is that because I'm attaching a seperate method to airport.airlines, when my script iterates over the table it reads the method also, causing the error.

What can I do to prevent this? I know swapping the two around would work but that's not a clean solution.

Thanks for your time.

airport.airlines = {
    Airline = {
        Destinations = {
            airport.destinations.Zakynthos;
        }
    }
}

function airport.airlines:GetAirlines()
    -blah
end

for i, v in pairs(airport.airlines) do

    function v:GetDestinations()
        --blah
    end

end

1 answer

Log in to vote
2
Answered by 7 years ago
Edited 7 years ago

Well, as you probably know, your loop is reading the function GetAirlines. This can be avoided by using type. Here's an updated version of your code:

airport.airlines = {
    Airline = {
        Destinations = {
            airport.destinations.Zakynthos;
        }
    }
}

function airport.airlines:GetAirlines()
    --blah
end

for i, v in pairs(airport.airlines) do
    if type(v) ~= "function" then
        function v:GetDestinations()
            --blah
        end
    end
end

0
thanks! ausmel105 140 — 7y
0
Also, would a metatable work in preventing this from happening. Because it makes values "hidden"? ausmel105 140 — 7y
0
It's not that they're "hidden" so much as `pairs` doesn't look there BlueTaslem 18071 — 7y
Ad

Answer this question