How to Install Lua and Bridge C with Lua on Ubuntu: Step‑by‑Step Guide
This tutorial walks you through installing Lua on Ubuntu, creating a convenient symlink, then demonstrates both calling Lua functions from C and invoking C functions from Lua, complete with compilation commands and expected output screenshots.
Installing Lua on Ubuntu
Before writing any code, install the Lua runtime and development headers:
sudo apt-get install lua5.1 sudo apt-get install lua5.1-0-devVerify the installation with lua -v to display the version.
Optionally, create a symbolic link for easier invocation:
ln -s lua5.1 luaPart 1: Calling Lua Functions from C (Ubuntu)
1. Create add.c containing the C code that will embed Lua and call a Lua function.
2. Write the Lua function in add.lua (e.g., a simple addition function).
3. Compile the C program and link against the Lua library: gcc -o add add.c -I /usr/include/lua5.1 -llua5.1 The resulting add executable can be run to test the integration.
Part 2: Calling C Functions from Lua (Ubuntu)
1. Write a Lua script hello.lua that will load a C shared library.
2. Implement the C side in power_lua.c, exposing the desired function.
3. Build a shared object that Lua can load:
gcc -Wall -shared -fPIC -o power.so -I/usr/include/lua5.1 power_lua.cThis creates power.so in the current directory.
4. Run the Lua script: lua hello.lua The script loads power.so and calls the C function, displaying the expected result.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
ITPUB
Official ITPUB account sharing technical insights, community news, and exciting events.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
