I am trying to create a script in which a list of values in table are references based on the index the percentage value a player chooses. However, for certain indexes, it keeps returning a nil value, and so far I cannot figure out a solution. Would anyone mind taking a look at it and find a possible solution?
local percentage = 0.1 local list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} while percentage < 1 do print(list[percentage * 10]) percentage = percentage + 0.1 wait() end --for index 3, 8, and 10, the table outputs nil.(list[percentage * 10]) = nil) print("----------------------------------") local num = 1 print(list[0.1 * 10]) print(list[0.2 * 10]) print(list[0.3 * 10]) print(list[0.4 * 10]) print(list[0.5 * 10]) print(list[0.6 * 10]) print(list[0.7 * 10]) print(list[0.8 * 10]) print(list[0.9 * 10]) print(list[1 * 10]) --This works perfectly fine, outputting all components of the table.
After some testing I realized roblox sometimes has this weird problem where lets say you do 2+2 and your answer will be 4, but in the computer it's actually something like 4.00000000000001. I'm not sure why it does this, but that's the issue here. When I did
while percentage < 1 do print(percentage) print(percentage * 10) local product = percentage * 10 print(list[percentage * 10]) numFloor = math.floor(product) print(list[numFloor ]) print(numFloor) percentage = percentage + 0.1 wait() end
print(list[numFloor ]) never resulted in a nil number. The only problem is lets say .3x10=3.000000001 mathfloor would change it to 3, but sometimes .7x10 = 6.99999999998 or something like that, so then the number will become 6.
To combat this you can use this
local function round(n) return math.floor(n + 0.5) end
Final working script:
local percentage = 0.1 local list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} local function round(n) return math.floor(n + 0.5) end while percentage < 1 do local product = round(percentage * 10) print(list[product]) percentage = percentage + 0.1 wait() end --for index 3, 8, and 10, the table outputs nil.(list[percentage * 10]) = nil) print("----------------------------------") local num = 1 print(list[0.1 * 10]) print(list[0.2 * 10]) print(list[0.3 * 10]) print(list[0.4 * 10]) print(list[0.5 * 10]) print(list[0.6 * 10]) print(list[0.7 * 10]) print(list[0.8 * 10]) print(list[0.9 * 10]) print(list[1 * 10])