Embedding Tiny
Apaar Madan edited this page Sep 5, 2022
·
1 revision
The Tiny API consists of a handful of functions which are documented in tiny/include/tiny.h
.
Let's start with a simple example: binding a single function.
#include <tiny.h>
// Define a C function that can be called from Tiny.
static TINY_FOREIGN_FUNCTION(Add) {
return Tiny_NewInt(Tiny_ToInt(args[0]) + Tiny_ToInt(args[1]));
}
int main(int argc, char** argv) {
// The Tiny_State houses all the data needed to compile and run your code.
Tiny_State* state = Tiny_CreateState();
// By default, there are no bindings exposed to the Tiny_State.
// The standard modules can be exposed by calling the Tiny_BindStandard*
// functions.
// Here, we provide access to `printf` (and other IO functions).
Tiny_BindStandardIO(state);
// We bind the Add function we defined above. Note how the binding is
// statically typed. You can look at `Tiny_BindFunction` in `tiny.h`
// for more details on the signature syntax.
Tiny_BindFunction(state, "add(int, int): int", Add);
// You can also bind constants, including strings and integers.
// Now we compile some simple code.
Tiny_CompileString(state, "example_1",
"x := 10; "
"y := x + 10; "
"printf(\"%i\\n\", add(x, y));"
);
// We could call Tiny_CompileString with the same state again. Code in
// subsequent calls would have access to code in previous ones.
// In order to execute code, we have to use a Tiny_StateThread.
// These are essentially lightweight VMs which execute the code
// within a Tiny_State. You can have many of them (e.g. one for
// every object within your game, one for every network request
// etc).
Tiny_StateThread thread;
// This will set up the thread with the state we just created.
// Note that threads do not mutate state at all, so you can
// run them with the same state across multiple OS threads, for
// example.
Tiny_InitThread(&thread, state);
// In order to run global code (i.e. code not within any function)
// we must call `Tiny_StartThread`. You can also call
// `Tiny_CallFunction` if you want to run a specific Tiny function.
Tiny_StartThread(&thread);
// Now we run the thread VM until it finishes. Each call to
// `Tiny_ExecuteCycle` runs a single instruction in the VM, so
// you can interleave/interrupt execution easily.
while(Tiny_ExecuteCycle(&thread));
// You should see:
// 30
//
// printed to your console.
// We can clean up the thread with `Tiny_DestroyThread`.
Tiny_DestroyThread(&thread);
// And we delete our state with `Tiny_DeleteState`.
Tiny_DeleteState(state);
return 0;
}
As you can see, it's pretty straightforward to get going. Take a look at the examples
directory for more comprehensive examples, and tiny.h
for the complete binding API.