Hey!
I'm relatively new to lua and am currently having an issue.
I have a table called carScrapperConfig, which shows the following.
carScrapperConfig = {}
carScrapperConfig[1] = {class = "airtugtdm", price = 1000}
carScrapperConfig[2] = {class = "mitsuevoxpoltdm", price = 2000}
Basically, I want to check if the class exists in the config, and if so then set it to a variable. If not then set the price to a random integer.
I have a for loop and if statement:
for k, v in pairs(carScrapperConfig) do
end
if table.HasValue(carScrapperConfig, "airtugtdm") then
carName = v.class
carPrice = v.price
print("in config", carPrice, carName)
else
print("not in config", carPrice, closestCarClass)
end
Because of what I'm seeing as the nature of your data, I recommend you use string keys for your table representing the class, and have the value be the price. That way you can check the class directly and assign a default value. Here's what I mean ( with example )
carScrapperConfig = {}
carScrapperConfig[ "airtugtdm" ] = 1000
/*
carScrapperConfig[ "STRINGKEY" ] = NUMBER
*/
Then you could assign the price as:
local price = carScrapperConfig[ currentclass ] or DEFAULT_VALUE
--Where currentclass is a variable representing the desired class and DEFAULT_VALUE represents whatever you want the fallback price to be
Should come out a lot smoother!
A better config in my opinion:
carScrapperConfig = {
"airtugtdm" = { price = 1000 },
"mitsuevoxpoltdm" = { price = 2000 }
}
You have technically already set the classes price variable in the config. You could just access it like this:
for _, carClass in pairs(carScrapperConfig ) do
if( carClass == nil ) then return end
print( carClass.price )
end
Thanks ;) I'll try it out tommorow
Would I put the "price" variable in a for loop?
You don't need to loop through the table at all if you know what classname you are looking for. I'm assuming classname is some variable of a gamemode judging by the tdm/dm I see there, so I'm also assuming you have these saved somewhere.
The price variable is written in such a way that it will check the table to see if that classname exists, and if so assign that value to the variable. If not, it will assign it to the default variable
You should only be using for loops if you are unsure of what entry you are looking for / want to process data inside of it
Ok thanks. I'm assuming I replace DEFAULT_VALUE with the variable I want if it doesn't find the currentClass in the config?
This prints nil by the way: print(carScrapperConfig["airtugtdm"])
Sorry, you need to Log In to post a reply to this thread.