GE Lua Documentation

Press F to search!

executeLuaSandboxed

Definition


-- @/lua/common/devUtils.lua:10
-- This Source Code Form is subject to the terms of the bCDDL, v. 1.1.
-- If a copy of the bCDDL was not distributed with this
-- file, You can obtain one at http://beamng.com/bCDDL-1.1.txt

-- development utility things
-- generally things that are not used so commonly to justify them being in util

-- safe lua function execution with IO overrides
-- NOTE: this cannot be conceptually safe as you can always get hidden objects
function executeLuaSandboxed(cmd, source)
  source = source or 'executeLuaSandboxed'
  local stdOutCache = {}

  -- sandbox creation
  local fEnv = getfenv(1) -- we reuse the environment and override only some things ...
  -- sandboxed functions
  local print_saved = fEnv.print
  fEnv.print = function(msg)
    --io.write("sandboxed print: " .. tostring(msg) .. "\n")
    table.insert(stdOutCache, tostring(msg))
  end

  -- parse the lua, fEnd is the tiny sandbox that we have to redirect stdout
  local func, err = load(cmd, source, 't', fEnv)

  -- execute the lua
  if func then
    if type(debug.traceback) ~= "function" then
      fEnv.print = print_saved
      return "Error: Lua debug traceback broken"
    end

    local ok, result = xpcall(func, debug.traceback)
    if ok then
      fEnv.print = print_saved
      return result, stdOutCache
    end

    fEnv.print = print_saved
    return "Error: " .. tostring(result)
  end
  fEnv.print = print_saved
  return "Error: " .. tostring(err)
end

Callers

@/lua/ge/extensions/ui/console.lua
              log("I", "exec", "GELua(Sandboxed) < "..dumps(cmd))
              local res, out = executeLuaSandboxed(cmd, 'GEConsole')
              --print(" RES = " .. tostring(res))