Code: Select all
local lastTime = false
local timewhenstarted = love.timer.getTime()
local time = 0
local CPUspeed = 20 --MHz, the virtual-computer
local realCPUspeed = 3 * 3200 --MHz, my computer
local sleepAfter = CPUspeed / realCPUspeed
function wait()
local microtime = love.timer.getTime()
if lastTime then
time = time + ( microtime - lastTime )
if time > sleepAfter then
love.timer.sleep( sleepAfter * ( realCPUspeed / CPUspeed - 1 ) )
microtime = microtime + sleepAfter * ( realCPUspeed / CPUspeed - 1 )
time = time - sleepAfter
end
end
lastTime = microtime
if microtime - timewhenstarted > 10 then
print( "loops per second: " .. math.floor( a/10 ) .. "\n" )
os.exit()
end
end
function transformCode(code)
local i = 0
local functname = "wait()"
local commandsToCheck = {"end", "else", "elseif"}
local string = code
for i,v in ipairs(commandsToCheck) do
while true do
i, j = string.find(string .. " ", v, i + 2 + #functname)
if i == nil then
break
end
string = string.sub(string, 1, i - 1) .. functname .. " " .. string.sub(string, i, #string)
end
end
--remove all \n
while true do
i, j = string.find(string, "\n")
if i == nil then
break
end
string = string.sub(string, 1, i-1) .. " " .. string.sub(string, i+1, #string)
end
return string
end
local original_code = "a = 0\nwhile true do\n a = a + 1\nend"
local code = transformCode( original_code .. " " )
print("\nORIGINALCODE:\n" .. original_code .. "\n\nCODE:\n" .. code .. "\n")
local func, msg = pcall( loadstring( code ) )
if func then
func()
else
print("ERROR: " .. msg)
end
original_code is the code which can be written by the player. Because the player can write several lines, my "transformCode()" delete all "\n"
realCPUspeed is your PC, I need a library to check this automatically
CPUspeed is the speed of the ingame-computer. I type 20 MHz, this is very slow.
For this example, I will stop the code in the wait() function and print out the progress.