1
votes

I have an embedded Lua instance from a game without external DLL support. I want to call a program from Lua, which creates a second Lua instance. My question is how to call any program in Lua? I think an "os.execute()" solution would be bad(restricted os.library on some machines).

1
Realize that even if you could call an external program, which it sounds like the game developer has disabled, that it wouldn't be associated with the game. Therefore, any functions that are not built-in to the stock lua.exe will not be available.BMitch

1 Answers

11
votes

You don't need to start another Lua instance to run another Lua script1. If you just want to call another Lua script, you can use dofile(filename). If you want to do it in another environment (in 5.1), you can do something like this:

local f = assert(load(filename)) -- the assert makes the failure case
                                 -- an error
local env = {} --insert whatever globals you want the script to have

setfenv(f, env) --set the script function to execute with the table
                --you have constructed as its environment
f() --Run the script in the constructed environment

If you actually need to start another program (say, the interpreter for a different scripting language), you can't do it without using os.execute() (or io.popen(), another library function that captures the spawned program's input and output streams, which is even more restriction-worthy).

If you're writing your script for a game that doesn't remove os.execute(), however, it's safe to assume that function will be available on other users' machines: the Lua environment is maintained by the embedding application (the game itself) and not any other installation on the machine. When it comes to games, there are really four scenarios where you wouldn't be able to spawn processes:

  1. The game's developer has removed library functions like os.execute from the game's Lua script environment. In this case, Lua scripts aren't able to spawn processes by design: if it were still possible, there wouldn't be much point in restricting access to the functions.

  2. The game runs in an operating environment where it can't spawn child processes (such as a restricted server account). In this case, the game couldn't start other programs even if it wanted to, as it's prohibited at the operating system level.

  3. The game is portable to multiple platforms, and the processes you'd need to spawn aren't available on all target platforms.

  4. The end-user has implemented their own sandbox for scripts that they run. In this case, the user can make the decision if they trust your script's need for os.execute enough to make an exception for it.

1: Any script you would run in this fashion would only have the base lua facilities and no connection to your parent script- assuming the user even has the standalone lua interpreter installed and in their PATH, which is unlikely in the Windows game environment.