This chapter covers intermediate techniques of API construction in Lua. We’ll see how to pass function arguments from C to Lua, how to work with Lua tables, and how to implement API functions in Lua instead of C.
In Lua, you can pass as many arguments to a function as you like. Even if the function is defined to accept three parameters, for example, you can pass in one or four, or even no arguments when you call it.
You can achieve this same flexibility from C at runtime. Chapter 2 briefly introduces
lua_call(), and because this is such a useful function, it’s worthwhile to take a more detailed look at it here. Following is the general technique for calling a Lua function from C, written with an example call to
print(1, 2, ’three’):
// 1. Push the Lua function onto the stack. lua_getglobal(L, "print"); // 2. Push the arguments, in order, onto the stack. lua_pushnumber(L, 1); lua_pushnumber(L, 2); lua_pushstring(L, "three"); // 3. Call the function. // You must also indicate how many return values you'd like. lua_call(L, 3, 0); // 3 = #input values; 0 = #output values. // The result on stdout is: // 1 2 three
When I play games, I love having the ability to influence the outcome of the game by pressing buttons. Let’s add this feature to EatyGuy. In particular, we can use C’s
getchar() function to get key codes, and pass those into the