Call the Lua Function

Source: Internet
Author: User
Translation from http://gamedevgeek.com/tutorials/calling-lua-functions/

Call the Lua Function

This is the second tutorial series of Lua script language. In the first article, we learned how to compile and run "Hello, world!" in Windows and Linux! "Program. If you have not read it, refer to the Lua introduction.

This tutorial covers lua5.1. Each Lua version has some very different features. The following Sample Code cannot be run in the old version of Lua. If you are still using the old version and do not want to upgrade it, don't worry. I have provided the source code download connection for the 4.0 and 5.0 tutorials at the bottom of the article. Okay, let's get started!

This article will teach you how to define a function in Lua and then call it in the C/C ++ program. At the same time, we will learn how to pass parameters, return values, and process global variables.

Your first Lua Function

Defining a function in Lua is quite simple. The Lua function starts with the keyword "function", followed by the function name, followed by the parameter list. The Function Definition ends with the keyword "end. The Lua function can accept multiple parameters and return multiple parameters.

The following is a Lua function that adds two numbers and returns results. Save it as the "Add. Lua" file.

-- add two numbers
function add ( x, y )
return x + y
end

In getting started with Lua, we know that calling lual_dofile () is to execute the script. Because we have defined only one function in this article, we only need to simply call the lual_dofile () function to execute the Add function.

As I have mentioned earlier, the Lua function can accept multiple parameters and return multiple results. This is implemented using stacks.

To call a Lua function, you must first push the function into the stack. Then press the parameter. Then, call lua_call () to call the Lua function. After the function is called, the returned value is stored in the stack. All these steps are displayed in the luaadd () function definition.

  1. Call lua_getglobal () to push the add () function into the stack.
  2. Call lua_pushnumber () to press the first parameter X into the stack.
  3. Similarly, call lua_pushnumber () to push the second parameter Y to the stack.
  4. When you call lua_call (), the parameter indicates two parameters and one return value.
  5. Now we can use lua_tointeger () to obtain the integer return value.
  6. Finally, call lua_pop () to remove the value from the stack.

Save the file as luaadd. cpp. If you directly use C instead of C ++, change the file name to luaadd. C and delete extern "C.

# Include <stdio. h>

Extern "C "{
# Include "Lua. H"
# Include "lualib. H"
# Include "lauxlib. H"
}

/* Pointer to the Lua interpreter */
Lua_state * l;
Int luaadd (int x, int y)
{
Int sum;
/* Obtain the Lua function by name */
Lua_getglobal (L, "add ");
/* First parameter */
Lua_pushnumber (L, X );
/* Second parameter */
Lua_pushnumber (L, y );
/* Call the function to inform you that there are two parameters, one return value */
Lua_call (l, 2, 1 );
/* Get the result */
Sum = (INT) lua_tointeger (L,-1 );
Lua_pop (L, 1 );
Return sum;
}

Int main (INT argc, char * argv [])
{
Int sum;
/* Initialize Lua */
L = lua_open ();
/* Load the basic Lua database */
Lual_openlibs (L );
/* Load the script */
Lual_dofile (L, "add. Lua ");
/* Call The Lua function */
Sum = luaadd (10, 15 );
/* Display result */
Printf ("the sum is % d/N", sum );
/* Clear Lua */
Lua_close (L );
/* Pause */
Printf ("press enter to exit... ");
Getchar ();
Return 0;
}

Compile

In Linux, type:

G ++ luaadd. cpp-llua-LDL-O luaadd

Then, run the following command:

./Luaadd

If there is no problem, the program will display the result: "The sum is 25 ".

In Visual C ++, perform the following steps:

  1. Create a new blank Win32 console application project.
  2. Add "luatest. cpp" to your project.
  3. Select properties from the project menu.
  4. Enter "lua5.1.lib" in "add dependencies" in "input" of "connector ".
  5. OK.

In this case, follow F7 to build the program.

If you are using a dll library, make sure that it is stored in the application directory or where it can be found in windows. If you are using a static Connection Library, you do not need.

Global Variables

Global variables are also well processed in Lua. As we can see, lua_getglobal () pushes a Lua global variable into the stack. For example, if the Lua script contains a global variable Z, the function of the following code is to get its value:

lua_getglobal(L, "z");
z = (int)lua_tointeger(L, -1);
lua_pop(L, 1);

Accordingly, the lua_setglobal () function can set the Location Value of a global variable. The following code demonstrates how to change the value of Lua global variable Z to 10:

lua_pushnumber(L, 10);
lua_setglobal(L, "z");

Remember: in Lua, there is no need to explicitly define a global variable. If the global variable does not exist, call lua_setglobal () to create one for you.

(This article is translated by groov0v. For more information, see the source !)

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.