[SOLVED] Make loops time out under environment?

User avatar
octacian
Member
 
Posts: 408
Joined: Mon Dec 21, 2015 22:18
GitHub: octacian
IRC: octacian
In-game: octacian

[SOLVED] Make loops time out under environment?

by octacian » Tue Jan 31, 2017 02:20

I've been working on a computer mod (digicompute), but have been having some issues with the environment. Everything works fine, but if the player creates a large/infinite loops (e.g. for i=1,100000 do ... end), the server crashes instead of the code nicely timing out as had been hoped.

My code for actually executing code under the environment:
Your phone or window isn't wide enough to display the code box. If it's a phone, try rotating it to landscape mode.
Code: Select all
  if code:byte(1) == 27 then
    return nil, "Binary code prohibited."
  end
  local f, msg = loadstring(code)
  if not f then return false, msg end
  setfenv(f, env)

  -- Turn off JIT optimization for user code so that count
  -- events are generated when adding debug hooks
  if rawget(_G, "jit") then
    jit.off(f, true)
  end

  -- Use instruction counter to stop execution
  -- after 10000 events
  debug.sethook(function()
    return false, "Code timed out!"
  end, "", 10000)
  local ok, ret = pcall(f)
  debug.sethook()  -- Clear hook
  if not ok then return false, ret end
  return true, ret


As you might guess, that's based off the Mesecons LuaController code.

I've tried using error() as do LCs, but it messes a ton of other stuff up. The computer itself is expecting this function to return two variables, 1: successful (boolean), and 2: result message.

Anyways, if someone could give me a hand, it'd be greatly appreciated. If you'd like to test yourself, see the digicompute thread linked at the top of this post.
God isn't dead!

My Coolest Mods:
MicroExpansion, Working Computers, Interchangeable Hands

Check out my YouTube channel! (octacian)
 

User avatar
octacian
Member
 
Posts: 408
Joined: Mon Dec 21, 2015 22:18
GitHub: octacian
IRC: octacian
In-game: octacian

Re: [SOLVED] Make loops time out under environment?

by octacian » Tue Jan 31, 2017 06:08

Got it working. Turned out that the issue was somewhere else, though I don't know where. After resetting my working directory, replacing return false, ... with error(..., 2) worked just fine.

Thanks kaeza!
God isn't dead!

My Coolest Mods:
MicroExpansion, Working Computers, Interchangeable Hands

Check out my YouTube channel! (octacian)
 


Return to Modding Discussion

Who is online

Users browsing this forum: No registered users and 5 guests

cron