hello I need help with my code, I am trying to make an if statment
times = ["1.94, 9.3, 3.4, 20.4"]
if tostring(9.3) in times then --thats where I got an error (incomplete statement: expected assignment or a function call)
end
hello I need help with my code, I am trying to make an if statment
times = ["1.94, 9.3, 3.4, 20.4"]
if tostring(9.3) in times then --thats where I got an error (incomplete statement: expected assignment or a function call)
end
I’m assuming you came from python
you can’t add “in” in an if statement in lua only “and” and “or”
and you don’t use “[]” for tables you suppose to use “{}”
times = {1.94, 9.3, 3.4, 20.4}
for i, v in pairs(times)do
if v == 9.3 then
print("Number found")
end
end
this will check if there is a specific number in the table
Luau actually has a built-in function for finding values in a table.
times = {1.94, 9.3, 3.4, 20.4} -- value type 'number'
if table.find(times, 9.3) then
print("Found")
end
table.find(tbl: table, value: any): number?
--> found something? return index
--> not found? return nil
does this work in also strings
Yes, it does, but the types have to match.
For instance, numberAsString
is a string, but we look for it in the times
table as a number - converted with tonumber()
. The original numberAsString
is still a string, because tonumber()
returns a variable of new type, and it’s returned into table.find()
.
--!strict
local numberAsString: string = "9.3"
local times: {number} = {1.94, 9.3, 3.4, 20.4}
if table.find(times, tonumber(numberAsString):: number) then
print("Found")
end
On the contrary, looking for “9.3” in the table without converting would not work.