Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to call C function in Lua

Shulou Source: shulou.com Published: 2022-06-02 09:40:02 10月17日 Update

This article will explain in detail how to call C function in Lua. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

Lua calls functions in C language to pass parameters through the stack, which is consistent with the implementation of internal function calls in most programming languages.

# include

# include

# include

# include

# include

Static int i_add (lua_State * L)

{

/ / get the first function argument

Double a = luaL_checknumber (L, 1)

Printf ("first parameter:% f\ n", a)

/ / get the second function parameter

Double b = luaL_checknumber (L, 2)

Printf ("second parameter:% f\ n", b)

/ / set the value returned by the function

Lua_pushnumber (L, a + b)

/ / the number of values returned by the function, where the return value is 1

Return 1

}

Static int i_swap (lua_State * L)

{

Int I = lua_tointeger (L, 1)

Int j = lua_tointeger (L, 2)

Printf ("% d and% d swap position\ n", I, j)

Lua_pushinteger (L, j)

Lua_pushinteger (L, I)

Return 2

}

/ / calculate the Fibonacci series

Static int i_fib (lua_State * L)

{

/ / the lua_Integer length is 64 bits to prevent overflow (in fact, even 64 bits will overflow when the value of n reaches 100 or so)

Lua_Integer sum = 0

Lua_Integer a = 0; / / n-2

Lua_Integer b = 0; / / n-1

Int n = lua_tointeger (L, 1)

Int I = 0

While (I n)

Return sum

End

N = 10000000-the number of Fibonacci series calculated

-- calculate using lua

Start = current_time ()

Fib_lua (n)

LuaCost = current_time ()-start

Print (luaCost)

-- using C language to calculate

Start = current_time ()

Fib_c (n)

CCost = current_time ()-start

Print (cCost)

-- calculating the time-consuming ratio between lua and C language

Print (luaCost / cCost)

Execute lua test.lua to get the following result:

First parameter: 1.000000

Second parameter: 2.000000

3.0

2333 and 666swap positions

666 2333

1887

forty

47.175 on how to call the C function in Lua to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Tags: Functions parameters files languages sequences codes locations content articles more knowledge articles good consistent facts digits dynamics variables commands most Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Shulou Information Shulou Technology Shulou Tech Info Xiaomi