Hey Zilarrezko. Going briefly over the code (and I might be wrong), looks like you're coming from another language, probably C++.
Regarding speed optimizations, there several things to point out.
Lua is an interpreted language so you want to avoid duplicate operations/function calls, ex:
Code: Select all
if type(tonumber(string:sub(i, i))) == "number" then
recall = recall .. string:sub(i, i)
In C/C++ the "string.sub" call would be optimized by the compiler by storing and reusing the result in a temporary variable - since "string.sub" is a 'const' function. However with interpreted languages like Lua it would be executed twice.
This is rarely a bottleneck, but you you want to keep in mind that the Lua interpreter doesn't know what's 'const' and what isn't.
Performance issues are more likely to come from creating intermediate strings/tables like:
Code: Select all
recall = recall .. string:sub(i, i)
This could be alleviated by using pattern matching which is usually faster (than iterating char by char) and can 'capture' entire tokens.
Lua doesn't have 'switch' so large elseif statements could be optimized by using lookup tables, ex:
Code: Select all
if temp == "+" then
local x = table.remove(stack, #stack - 1)
local y = table.remove(stack, #stack)
table.insert(stack, #stack + 1, x + y)
elseif temp == "-" then
local x = table.remove(stack, #stack - 1)
local y = table.remove(stack, #stack)
table.insert(stack, #stack + 1, x - y)
elseif temp == "*" then
local x = table.remove(stack, #stack - 1)
local y = table.remove(stack, #stack)
table.insert(stack, #stack + 1, x * y)
elseif temp == "/" then
local x = table.remove(stack, #stack - 1)
local y = table.remove(stack, #stack)
table.insert(stack, #stack + 1, x / y)
end
could become:
Code: Select all
lookup = {}
lookup["*"] = function(a, b) return a*b end
lookup["/"] = function(a, b) return a/b end
lookup["+"] = function(a, b) return a+b end
lookup["-"] = function(a, b) return a-b end
local p2 = table.remove(stack)
local p1 = table.remove(stacK)
local res = lookup[Op_Token](p1, p2)
table.insert(stack, res)
Also, isn't
Code: Select all
table.insert(queue, #queue + 1, x)
the same as:
That's all I can come up with for now, hope it helps.
PS. Oh ya, and forgot to mention that local functions are faster, if you declare them at the beginning of the script ex: