lualuau

LuaU - Need to make this efficient, don't want to spam elseifs


Okay, so, I'm just curious on how to make this more efficent. I know it likely has something to do with a table loop like in pairs() or something. I know this is bad code, and I want to find a way to make it not bad.

if string.find(subject.Name, 0) then
    inVal.Value = 0
elseif string.find(subject.Name, 1) then
    inVal.Value = 1
elseif string.find(subject.Name, 2) then
    inVal.Value = 2
elseif string.find(subject.Name, 3) then
    inVal.Value = 3
elseif string.find(subject.Name, 4) then
    inVal.Value = 4
elseif string.find(subject.Name, 5) then
    inVal.Value = 5
elseif string.find(subject.Name, 6) then
    inVal.Value = 6
elseif string.find(subject.Name, 7) then
    inVal.Value = 7
elseif string.find(subject.Name, 8) then
    inVal.Value = 8
elseif string.find(subject.Name, 9) then
    inVal.Value = 9
end

Solution

  • You can parse the int value from the string using string.match and then use tonumber function on it.

    This would be more efficient then looping every possible answer.

    local match = string.match(subject.Name, "%d")
    inVal.Value = tonumber(match)