Fundamentals 4 min read

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.

ITPUB
ITPUB
ITPUB
How to Install Lua and Bridge C with Lua on Ubuntu: Step‑by‑Step Guide

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-dev

Verify the installation with lua -v to display the version.

Optionally, create a symbolic link for easier invocation:

ln -s lua5.1 lua

Part 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.c

This 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Integrationprogrammingc++TutorialUbuntu
ITPUB
Written by

ITPUB

Official ITPUB account sharing technical insights, community news, and exciting events.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.