I used to see how to write lua scripts, and I wrote them in the previous studio. I don't really understand how LUA interacts with C. I wrote an example today.
First, I want to implement the function to calculate the sum of two integers, that is, x + y. Because x and y are changing at any time, and I don't want to modify them in the C program, I will put these two parameters in the lua script for transmission.
So how do I implement it?
Step 1: Set up the window environment. Use vs2005 to search online.
Step 2: Write down the logic of the c function.
[Cpp]
// Testlua. c
# Include "stdafx. h"
# Include <stdio. h>
Extern "C "{
# Include "lua. h"
# Include "lualib. h"
# Include "lauxlib. h"
}
Lua_State * L;
Int add (lua_State * L );
Int add (lua_State * L)
{
// Retrieve the value with an index of 1 from the L stack and check
Int x = luaL_checkint (L, 1 );
// Retrieve the index 2 value from the L stack and check
Int y = luaL_checkint (L, 2 );
Printf ("result: % d \ n", x + y );
Return 1;
}
Int _ tmain (int argc, _ TCHAR * argv [])
{
// Initialize global L
L = luaL_newstate ();
// Open the library
LuaL_openlibs (L );
// Push the function into the stack
Lua_pushcfunction (L, add );
// Set global ADD
Lua_setglobal (L, "ADD ");
// Load our lua script file
If (luaL_loadfile (L, "E: \ work \ vsProject \ testLua \ mylua. lua "))
{
Printf ("error \ n ");
}
// Security check
Lua_pcall (L, 0, 0 );
// Push to lua Function
Lua_getglobal (L, "mylua ");
Lua_pcall (L, 0, 0 );
Printf ("hello my lua \ n ");
Return 0;
}
Below is my lua script code, which is very simple.
[Html]
Function mylua ()
Print ("mylua ")
ADD (1, 2)
ADD (3, 4)
End
ADD (1, 2) is associated with the registered add function, and the parameter is pushed in.
The output result is as follows:
Is it easy. Let's take a look at it.