Lua itself is positioned in a lightweight, flexible, expandable scripting language, which means you can freely expand Lua, tailor your own game to make a scripting language.
You can provide your own API to the script in the host program, which is called.
Lua defines a type: Lua_CFunction, this is a function pointer, its prototype is: typedef int (* Lua_State * L);
This means that only this type of function can be registered with Lua.
First, we define a function
INT foo (Lua_State * L) {// First take out the script to execute the stack when performing this function // assume that this function provides a parameter, there are two return values
// Get the first parameterconst char * par = Lua_toString (L, -1);
Printf ("% S / N", PAR);
// push the first resultlua_pushnumber (l, 100);
// push the second resultlua_pushnumber (l, 200);
// Return 2 ResultReturn 2;}
We can call this function in the script.
R1, R2 = foo ("Hello")
Print (R1..R2)
The complete test code is as follows:
#include "lua.h" #include "lauxlib.h" #include "lualib.h"
INT foo (Lua_State * L) {// First take out the script to execute the stack when performing this function // assume that this function provides a parameter, there are two return values
// Get the first parameterconst char * par = Lua_toString (L, -1);
Printf ("% S / N", PAR);
// push the first resultlua_pushnumber (l, 100);
// push the second resultlua_pushnumber (l, 200);
// Return 2 ResultReturn 2;}
INT Main (int Argc, char * argv []) {Lua_State * L = Lua_Open (); Luaopen_Base (L); LuaOpen_IO (L);
// This line is originally, this line is //. Thank Freerpg@sina.com to remind Lua_Register (L, "foo", foo);
Const char * buf = "r1, r2 = foo (" hello ") Print (R1..R2)";
Lua_Dostring (L, BUF);
Lua_Close (L);
Return 0;}
Program output: Hello100200