Examples of mutual calls between lua and C

Source: Internet
Author: User

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.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.