Skip to content

9. Exporting Functions

AsynchronousAI edited this page Sep 3, 2025 · 3 revisions

Fibonacci Sequence

Let us use the classic fibonacci sequence for this example:

#include <stdio.h>

int fibonacci(int n) {
    if (n == 0) return 0;
    if (n == 1) return 1;

    int a = 0, b = 1, next;
    for (int i = 2; i <= n; i++) {
        next = a + b;
        a = b;
        b = next;
    }
    return b;
}

int main() {
    int n = 5;

    printf("Fibonacci sequence up to %d terms:\n", n);
    for (int i = 0; i < n; i++) {
        printf("%d", fibonacci(i));
    }
    return 0;
}

Now if we run this, it will work like expected starting from main!

Fibonacci sequence up to 5 terms:

0
1
1
2
3

But what if we wanted our Luau function to directly invoke twoSum?

Analyzing Exports

With the --mode module option you can see this snippet of code at the end of the generated Luau program:

	exports = {
		["fibonacci"] = function() start(1) end,
		[".L3"] = function() start(2) end,
		[".L4"] = function() start(3) end,
		[".L5"] = function() start(4) end,
		[".L7"] = function() start(5) end,
		[".LC0"] = function() start(6) end,
		[".LC1"] = function() start(7) end,
		["main"] = function() start(8) end,
		[".L9"] = function() start(10) end,
	}

Well that makes things super easy!

-- INCORRECT USAGE:
local val = module.exports.fibonacci(5)
print(val) -- 3!

But not too quickly, In assembly the concept of parameters are extremely simplified.

Using it in Luau

I would recommend to create a Luau function wrapper around the Assembly function like so

function C_fibonacci(input: number)
   -- what to do here?
   return val
end

now we can trigger module.exports.fibonacci, but we must collect and provide values using the return_args and extract_args utilities.

function C_fibonacci(input: number)
   module.util.push_args(input) -- loads input as an integer into the argument register (return_args can take up to 7 ints)
   module.exports.fibonacci()
   return module.util.get_args()
end

push_args and get_args is used the same as from Advanced Custom Functions, which means you can use floating points, and strings!

Final Results

local module = require("./module")

function C_fibonacci(input: number)
   module.util.push_args(input) -- loads input as an integer into the argument register (return_args can take up to 7 ints)
   module.exports.fibonacci()
   return module.util.get_args()
end

print(C_fibonacci(10)) -- 55 (correct!)

Clone this wiki locally