Chapter 3. Using Lua Values in C

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.

EatyGuy Version 3: Passing Data to a Lua Function

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 eatyguy.loop() function.

Receiving Arrow Key Presses

Terminal-based ...

Get Creating Solid APIs with Lua now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.