마음의 안정을 찾기 위하여 - [Lua] Calling Lua Functions
2401024
41
340
관리자새글쓰기
태그위치로그방명록
별일없다의 생각
dawnsea's me2day/2010
색상(RGB)코드 추출기(Color...
Connection Generator/2010
최승호PD, '4대강 거짓말 검...
Green Monkey**/2010
Syng의 생각
syng's me2DAY/2010
천재 작곡가 윤일상이 기획,...
엘븐킹's Digital Factory/2010
[Lua] Calling Lua Functions
Web, Script/Lua | 2010/01/03 00:49
출처 : http://gamedevgeek.com/tutorials/calling-lua-functions/

This is the second in my series of tutorials covering the Lua scripting language. The first tutorial deals with setting up Lua on Windows and Linux and compiling your first “Hello, World!” program. If you haven’t been through the first tutorial yet, please read it now.

This tutorial now covers version 5.1 of Lua. There are some pretty major differences in each version of Lua. The code shown below will not work in older versions of Lua. If you are still using an older version and don’t want to upgrade, I have provided downloads for version 4.0 and 5.0 at the bottom of this tutorial. With that in mind, let’s get started.

This tutorial will show you how to define a funcion in a Lua script and call it from your C or C++ program. We will cover passing arguments, returning values, and deal with global variables.

Your first function in Lua

Defining functions in Lua is very simple. Start with the word “function”, followed by the function name, and a list of arguments. Function definitions end with the word “end”. Functions in Lua can accept multiple arguments and return multiple results.

Here’s a simple Lua function that adds two numbers and returns their sum. Save this file as add.lua

-- add two numbers

function add ( x, y )
return x + y
end

In the previous tutorial, the call to luaL_dofile() would execute the script. Since the Lua script in this tutorial only defines a function, calling luaL_dofile() simply makes the function available to our program.

As I said earlier, functions in Lua can accept multiple arguments and return multiple results. This is done using a stack.

To call a Lua funcion, we first push the function onto the stack. The function is followed by the arguments, in order. Then we call the function with lua_call(). After the function call, the return value is available on the stack. All of these steps are demonstrated in the luaadd() function below.

  1. The call to lua_getglobal() pushes the add() function onto the stack.
  2. The first argument, x, is pushed onto the stack with lua_pushnumber().
  3. The second argument, y, is pushed onto the stack with lua_pushnumer().
  4. Then the function is called with lua_call(). We specify two arguments and one return value.
  5. Now we retrieve the return value from the top of the stack with lua_tointeger().
  6. Finally, we remove the value from the stack with lua_pop().

Save this file as luaadd.cpp. If you’d like to use straight C instead of C++, just name the file luaadd.c and remove the extern “C”.

#include <stdio.h>

extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}

/* the Lua interpreter */
lua_State* L;

int luaadd ( int x, int y )
{
int sum;

/* the function name */
lua_getglobal(L, "add");

/* the first argument */
lua_pushnumber(L, x);

/* the second argument */
lua_pushnumber(L, y);

/* call the function with 2
arguments, return 1 result */

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 Lua base libraries */
luaL_openlibs(L);

/* load the script */
luaL_dofile(L, "add.lua");

/* call the add function */
sum = luaadd( 10, 15 );

/* print the result */
printf( "The sum is %d\\n", sum );

/* cleanup Lua */
lua_close(L);

/* pause */
printf( "Press enter to exit..." );
getchar();

return 0;
}

Compiling

On Linux you can compile this program by typing this command:

g++ luaadd.cpp -llua -ldl -o luaadd

Then run the program by typing:

./luaadd

If everything worked correctly, the program should print “The sum is 25″

In Visual C++ you’ll need to follow these steps:

  1. Create a new empty Win32 Console Application Project.
  2. Add the “luaadd.cpp” file to your project.
  3. On the menu click Project, luatest Properties.
  4. Expand “Configuration Properties”
  5. Expand “Linker”
  6. Click “Input”
  7. Beside “Additional Dependencies” type lua5.1.lib.
  8. Click OK

At this point, you should be able to press F7 to Build the program.

Before we can run the program, you’ll need to put the “lua5.1.dll” file where Windows can find it. Copy the file from “C:\Program Files\lua5.1\lib\dll” to your new Visual C++ project’s folder. If your program compiled without errors, you can now press F5 to execute the program.

Global Variables

Global variables are also easy to deal with in Lua. As we’ve seen, lua_getglobal() will push the value of a Lua global onto the stack. If our Lua script contained a global variable named z, for example, this piece of code would get it’s value:

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

There is also a corresponding lua_setglobal() function that sets the value of a global variable. This snippet of code demonstrates setting the value of the global Lua variable z to 10:

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

Note that it is not necessary to explicitly define global variables in your Lua script. Setting a value with lua_setglobal() will create the global for you if it doesn’t already exist.

Downloads

Resources

For in depth coverage of the Lua programming language, see Programming In Lua by the creator of the language. Game Development With Lua was written by professional programmers using Lua in a game. If you’re interested in using other scripting languages in your game, or even creating your own language, check out Game

Older Versions

Here are the files for Lua 5.0.

Here are the files for Lua 4.0.

  • luaadd-4.zip – Tutorial Source and Project files for Visual C++ 6 on Windows.
  • luaadd-4.tar.gz – Tutorial Source and Makefile for Linux.

You should now be able to define functions in Lua and call them from your C++ programs. The next tutorial will cover calling C++ functions from Lua.


2010/01/03 00:49 2010/01/03 00:49
Article tag list Go to top
View Comment 0
Trackback URL :: 이 글에는 트랙백을 보낼 수 없습니다
 
 
 
 
: [1] ... [320][321][322][323][324][325][326][327][328] ... [1323] :
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31        
전체 (1323)
출판 준비 (0)
My-Pro... (41)
사는 ... (933)
블로그... (22)
My Lib... (32)
게임 ... (23)
개발관... (3)
Smart ... (1)
Delphi (93)
C Builder (0)
Object... (0)
VC, MF... (10)
Window... (1)
Open API (3)
Visual... (0)
Java, JSP (2)
ASP.NET (0)
PHP (6)
Database (12)
리눅스 (29)
Windows (25)
Device... (1)
Embedded (1)
게임 ... (0)
Web Se... (2)
Web, S... (21)
잡다한... (7)
프로젝트 (0)
Personal (0)
대통령... (13)
Link (2)