1. ホーム
  2. スクリプト・コラム
  3. ルア

lua基本チュートリアル

2022-01-06 17:54:52

最近luaを見ていて、最新版の例がないのが気になったので、他の人のブログからソースコードをもらってきて、lua C APIの最新版に変更しました。

まずは、luaの超基本には触れずに、簡単なテストから始めてみましょう。

その前に、Win32でluaの環境がない場合は、以下のサイトを参照してください。 https://www.jb51.net/article/61451.htm

1. luaスクリプトのC/C++実行

最新のC API for luaに切り替えたばかりなので、さっそくコードを見てみましょう

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
extern "C"
{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
};
using namespace std;
int main()
{
lua_State *pLuaState = luaL_newstate();
/* load lua base library */
luaL_openlibs(pLuaState);
//luaopen_base(pLuaState);
//luaopen_io(pLuaState); //replace the old lua_iolibopen(pLuaState);
//luaopen_string(pLuaState); //replace the old lua_strlibopen(pLuaState);
//luaopen_math(pLuaState); //replace the old lua_mathlibopen(pLuaState);
//luaopen_debug(pLuaState); //replace old lua_dblibopen(pLuaState);
/*run the script*/
luaL_dofile(pLuaState,". /script/hw.lua");
/* clear lua*/ 
lua_close(pLuaState);
/*pause*/
cout<<"Press enter to exit..."<<<endl;
getchar();
return 0;
}



hw.luaのソースコードです。

print("Hello Word! ");


この例では、単純にluaスクリプトを実行しています。

ここで、lua_newstateはメモリ確保関数を必要とするコア関数、luaL_newstateはデフォルトのメモリ確保関数を使用するヘルパーライブラリ関数です。lua_openは5.0時代、5.1はluaL_newstateのマクロ、5.2はもう入っていないそうです。

2. C/C++によるlua関数の呼び出し

さっそく、コードを見てみましょう。

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
extern "C"
{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
};
using namespace std;
/************************************************************************/
//function function: call lua function
// function parameters.
// L lua virtual machine
// x
// y
// function returns.
// sum
// core function lua_call()
/*
Calls a function.
To call a function follow the following protocol: first, the function to be called should be stacked; next, the arguments to be passed to the function should be stacked in positive order.
This means that the first argument is stacked first. Finally, call lua_call; nargs is the number of arguments you pressed onto the stack. When the function is called, all the arguments and the function itself are off the stack.
The return value of the function is then pushed onto the stack. The number of return values will be adjusted to nresults unless nresults is set to LUA_MULTRET.
In this case, all return values are pushed onto the stack. Lua will ensure that the return values are placed on the stack space.
Function return values are stacked in positive order (the first return value is stacked first), so that at the end of the call, the last return value is placed on the top of the stack.
Errors within the called function are always thrown up (via longjmp).
*/
/************************************************************************/
int luaadd(lua_State *L, int x, int y)
{
int sum;
/* Get Lua functions by name */
lua_getglobal(L,"add");
/* press the first argument onto the stack */
lua_pushnumber(L,x);
/*push the second argument onto the stack*/
lua_pushnumber(L,y);
/* call the function */
lua_call(L,2,1);
/* Get the result
Converts the Lua value at the given index to a signed integer type like lua_Integer.
The Lua value must be a number or a string that can be converted to a number, otherwise, lua_tointeger returns 0. */
sum = (int)lua_tointeger(L,-1);
/* pop n elements from the stack */
//n
lua_pop(L,1);
return sum;
}
int main()
{
int sum;
/* initialize the lua virtual machine */
lua_State *L = luaL_newstate();
/* load lua base library */
luaL_openlibs(L);
/* load script */
luaL_dofile(L,". /script/test.lua");
/* call lua functions*/
sum = luaadd(L,10,15);
/*Display the result*/
cout<<"The sum = "<<sum<<endl;
/*clear the lua virtual machine*/
lua_close(L);
/*Show results and pause*/
cout<<"Press enter to exit..."<<<endl;
getchar();
return 0;
}


test.luaのコードです。

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



luaのスタックに関する問題の1つは、まだ理解できていないことなので、詳しく教えてほしい。

3. luaはC/C++の関数を呼び出す

そのコードは

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
extern "C"
{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
};
using namespace std;
static int average(lua_State *L)
{
/* get the number of arguments */
int n = lua_gettop(L);
/* define and */
double sum = 0;
/* loop variable*/
int i;
/* loop summation */
for (i = 1; i <= n; i++)
{
sum += lua_tonumber(L,i);
//cout<<sum<<endl;
}
//cout<<"ffffff"<<<endl;
/*pushnumber*/
lua_pushnumber(L,sum/n);
/*push in and*/
lua_pushnumber(L,sum);
/* return the number of returned values */
return 2;
}
int main()
{
/* initialize the Lua virtual machine */
lua_State *L = luaL_newstate();
/* open lua basic library */
luaL_openlibs(L);
/* register function */
lua_register(L,"average",average);
/*run script*/
luaL_dofile(L,". /script/avg.lua");
/* clear the lua virtual machine*/
lua_close(L);
/* print pause*/
cout<<"Press enter to exit..."<<<endl;
getchar();
return 0;
}



avg.luaのソースコードです。

function main()
local avg,sum = average(2,2,2,2,2);
print("The avg is",avg);
print("The sum is", sum);
end
main();