When I start learning Lua embedding C, I usually write such a small program to perform a script file:
Code:
INT _Tmain (int Argc, _tchar * argv [])
{
// Open Lua State
Lua_State * L = Lua_Open ();
Luaopen_Base (L);
// load script file
LUAL_LOADFILE (L, "script.lua");
Lua_Resume (L, 0);
// Call Foobar
Lua_GETGLOBAL (L, "FOOBAR");
Lua_Pushnumber (L, 211);
IF (Lua_Resume (L, 1))
Printf ("% S / N", Lua_ToString (L, 1));
// Close IT
Lua_Close (L);
Return 0;
}
The corresponding Lua script may be like this
Code:
Function foobar ()
Print ("foobar!")
end
This procedure is very simple, the result of run is to output a string foobar! There will be a sentence immediately after the program loadfile: Lua_Resume (L, 0); when I started learning it, I think of course to implement a script file. The function, must Resume will make the script valid, otherwise any statement will not let it execute (describe a bit problem), in the later understanding, is not the case. When LUAL_LOADFILE (actually calls Lua_Load functions), Lua_Resume is not required, why? LUA_LOAD After reading a piece of script, putting something as an anonymous function on the top, so call Lua_Resume (L, 0); will perform this function and then see what Lua_Resume has done something very clear: First By default, the current execution environment for executing a Lua script is the global table, that is, the _g, executes this function (code file code), so it will be the definition of the Function. The function of the function added to the execution of this function (the code of the script file) is obvious, Lua_getglobal (L, "FOOBAR") found this function and then execute. And if you don't call Lua_Resume (L, 0) after LOADFILE, then you can't find FOOBAR in the later Lua_GETGLOBAL (return value is a Lua_Tnil), which will fail.
If there is a single function corresponding to a script file, I definitely want to output a simple string such as "FOOBAR!", I don't want to enter the word foobar () this word (or I want the script writer) You can be executed directly to write a script) So you may have the following lua code.
Code:
Print ("foobar!")
Suppose this script file is named FOOBAR function, you can write this in the program.
Code:
Lua_PushString (L, "FOOBAR");
LUAL_LOADFILE (L, "script.lua");
Lua_rawset (L, Lua_GlobalSindex); // Under normal circumstances, Lua_SetTable can also
// Call Foobar
Lua_GETGLOBAL (L, "FOOBAR");
IF (Lua_Resume (L, 0)) Printf ("% S / N", Lua_TOString (L, 1));
There is no Lua_Resume here, but instead of using a Lua_rawset.
Author: Wind Dances days Transfer: Lua Chinese website (www.luachina.net)