Support for Lua added - patch from Mark Gossage

git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/trunk@7365 626c5289-ae23-0410-ae9c-e8d60b6d4f22
This commit is contained in:
William S Fulton 2005-08-15 20:58:56 +00:00
commit 127e49e03b
27 changed files with 2266 additions and 0 deletions

View file

@ -0,0 +1,4 @@
# see top-level Makefile.in
class
simple
variables

View file

@ -0,0 +1,19 @@
TOP = ../..
SWIG = $(TOP)/../swig
CXXSRCS = example.cxx
TARGET = example
INTERFACE = example.i
LIBS = -lm
all::
$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua_cpp
static::
$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
TARGET='mylua' INTERFACE='$(INTERFACE)' lua_cpp_static
clean::
$(MAKE) -f $(TOP)/Makefile lua_clean
check: all

View file

@ -0,0 +1,28 @@
/* File : example.c */
#include "example.h"
#define M_PI 3.14159265358979323846
/* Move the shape to a new location */
void Shape::move(double dx, double dy) {
x += dx;
y += dy;
}
int Shape::nshapes = 0;
double Circle::area(void) {
return M_PI*radius*radius;
}
double Circle::perimeter(void) {
return 2*M_PI*radius;
}
double Square::area(void) {
return width*width;
}
double Square::perimeter(void) {
return 4*width;
}

View file

@ -0,0 +1,39 @@
/* File : example.h */
class Shape {
public:
Shape() {
nshapes++;
}
virtual ~Shape() {
nshapes--;
};
double x, y;
void move(double dx, double dy);
virtual double area(void) = 0;
virtual double perimeter(void) = 0;
static int nshapes;
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) { };
virtual double area(void);
virtual double perimeter(void);
};
class Square : public Shape {
private:
double width;
public:
Square(double w) : width(w) { };
virtual double area(void);
virtual double perimeter(void);
};

View file

@ -0,0 +1,10 @@
/* File : example.i */
%module example
%{
#include "example.h"
%}
/* Let's just grab the original header file here */
%include "example.h"

View file

@ -0,0 +1,57 @@
-- file: runme.lua
-- This file illustrates class C++ interface generated
-- by SWIG.
-- importing (lua doesnt have a nice way to do this)
if example==nil then
assert(loadlib("example.dll","Example_Init"))()
end
----- Object creation -----
print("Creating some objects:")
c = example.Circle(10)
print(" Created circle", c)
s = example.Square(10)
print(" Created square", s)
----- Access a static member -----
print("\nA total of",example.Shape_nshapes,"shapes were created")
----- Member data access -----
-- Set the location of the object
c.x = 20
c.y = 30
s.x = -10
s.y = 5
print("\nHere is their current position:")
print(string.format(" Circle = (%f, %f)",c.x,c.y))
print(string.format(" Square = (%f, %f)",s.x,s.y))
----- Call some methods -----
print("\nHere are some properties of the shapes:")
for _,o in pairs({c,s}) do
print(" ", o)
print(" area = ", o:area())
print(" perimeter = ", o:perimeter())
end
print("\nGuess I'll clean up now")
-- Note: this invokes the virtual destructor
c=nil
s=nil
s = 3
-- call gc to make sure they are collected
collectgarbage()
print(example.Shape_nshapes,"shapes remain")
print "Goodbye"

439
SWIG/Examples/lua/lua.c Normal file
View file

@ -0,0 +1,439 @@
/*
** $Id$
** Lua stand-alone interpreter
** See Copyright Notice in lua.h
*/
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define lua_c
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
/*
** generic extra include file
*/
#ifdef LUA_USERCONFIG
#include LUA_USERCONFIG
#endif
/*
** definition of `isatty'
*/
#ifdef _POSIX_C_SOURCE
#include <unistd.h>
#define stdin_is_tty() isatty(0)
#else
#define stdin_is_tty() 1 /* assume stdin is a tty */
#endif
#ifndef PROMPT
#define PROMPT "> "
#endif
#ifndef PROMPT2
#define PROMPT2 ">> "
#endif
#ifndef PROGNAME
#define PROGNAME "lua"
#endif
#ifndef lua_userinit
#define lua_userinit(L) openstdlibs(L)
#endif
#ifndef LUA_EXTRALIBS
#define LUA_EXTRALIBS /* empty */
#endif
static lua_State *L = NULL;
static const char *progname = PROGNAME;
extern int Example_Init(lua_State* L);
static const luaL_reg lualibs[] = {
{"base", luaopen_base},
{"table", luaopen_table},
{"io", luaopen_io},
{"string", luaopen_string},
{"math", luaopen_math},
{"debug", luaopen_debug},
{"loadlib", luaopen_loadlib},
/* add your libraries here */
{"example", Example_Init},
LUA_EXTRALIBS
{NULL, NULL}
};
static void lstop (lua_State *l, lua_Debug *ar) {
(void)ar; /* unused arg. */
lua_sethook(l, NULL, 0, 0);
luaL_error(l, "interrupted!");
}
static void laction (int i) {
signal(i, SIG_DFL); /* if another SIGINT happens before lstop,
terminate process (default action) */
lua_sethook(L, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
}
static void print_usage (void) {
fprintf(stderr,
"usage: %s [options] [script [args]].\n"
"Available options are:\n"
" - execute stdin as a file\n"
" -e stat execute string `stat'\n"
" -i enter interactive mode after executing `script'\n"
" -l name load and run library `name'\n"
" -v show version information\n"
" -- stop handling options\n" ,
progname);
}
static void l_message (const char *pname, const char *msg) {
if (pname) fprintf(stderr, "%s: ", pname);
fprintf(stderr, "%s\n", msg);
}
static int report (int status) {
const char *msg;
if (status) {
msg = lua_tostring(L, -1);
if (msg == NULL) msg = "(error with no message)";
l_message(progname, msg);
lua_pop(L, 1);
}
return status;
}
static int lcall (int narg, int clear) {
int status;
int base = lua_gettop(L) - narg; /* function index */
lua_pushliteral(L, "_TRACEBACK");
lua_rawget(L, LUA_GLOBALSINDEX); /* get traceback function */
lua_insert(L, base); /* put it under chunk and args */
signal(SIGINT, laction);
status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base);
signal(SIGINT, SIG_DFL);
lua_remove(L, base); /* remove traceback function */
return status;
}
static void print_version (void) {
l_message(NULL, LUA_VERSION " " LUA_COPYRIGHT);
}
static void getargs (char *argv[], int n) {
int i;
lua_newtable(L);
for (i=0; argv[i]; i++) {
lua_pushnumber(L, i - n);
lua_pushstring(L, argv[i]);
lua_rawset(L, -3);
}
/* arg.n = maximum index in table `arg' */
lua_pushliteral(L, "n");
lua_pushnumber(L, i-n-1);
lua_rawset(L, -3);
}
static int docall (int status) {
if (status == 0) status = lcall(0, 1);
return report(status);
}
static int file_input (const char *name) {
return docall(luaL_loadfile(L, name));
}
static int dostring (const char *s, const char *name) {
return docall(luaL_loadbuffer(L, s, strlen(s), name));
}
static int load_file (const char *name) {
lua_pushliteral(L, "require");
lua_rawget(L, LUA_GLOBALSINDEX);
if (!lua_isfunction(L, -1)) { /* no `require' defined? */
lua_pop(L, 1);
return file_input(name);
}
else {
lua_pushstring(L, name);
return report(lcall(1, 1));
}
}
/*
** this macro can be used by some `history' system to save lines
** read in manual input
*/
#ifndef lua_saveline
#define lua_saveline(L,line) /* empty */
#endif
/*
** this macro defines a function to show the prompt and reads the
** next line for manual input
*/
#ifndef lua_readline
#define lua_readline(L,prompt) readline(L,prompt)
/* maximum length of an input line */
#ifndef MAXINPUT
#define MAXINPUT 512
#endif
static int readline (lua_State *l, const char *prompt) {
static char buffer[MAXINPUT];
if (prompt) {
fputs(prompt, stdout);
fflush(stdout);
}
if (fgets(buffer, sizeof(buffer), stdin) == NULL)
return 0; /* read fails */
else {
lua_pushstring(l, buffer);
return 1;
}
}
#endif
static const char *get_prompt (int firstline) {
const char *p = NULL;
lua_pushstring(L, firstline ? "_PROMPT" : "_PROMPT2");
lua_rawget(L, LUA_GLOBALSINDEX);
p = lua_tostring(L, -1);
if (p == NULL) p = (firstline ? PROMPT : PROMPT2);
lua_pop(L, 1); /* remove global */
return p;
}
static int incomplete (int status) {
if (status == LUA_ERRSYNTAX &&
strstr(lua_tostring(L, -1), "near `<eof>'") != NULL) {
lua_pop(L, 1);
return 1;
}
else
return 0;
}
static int load_string (void) {
int status;
lua_settop(L, 0);
if (lua_readline(L, get_prompt(1)) == 0) /* no input? */
return -1;
if (lua_tostring(L, -1)[0] == '=') { /* line starts with `=' ? */
lua_pushfstring(L, "return %s", lua_tostring(L, -1)+1);/* `=' -> `return' */
lua_remove(L, -2); /* remove original line */
}
for (;;) { /* repeat until gets a complete line */
status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "=stdin");
if (!incomplete(status)) break; /* cannot try to add lines? */
if (lua_readline(L, get_prompt(0)) == 0) /* no more input? */
return -1;
lua_concat(L, lua_gettop(L)); /* join lines */
}
lua_saveline(L, lua_tostring(L, 1));
lua_remove(L, 1); /* remove line */
return status;
}
static void manual_input (void) {
int status;
const char *oldprogname = progname;
progname = NULL;
while ((status = load_string()) != -1) {
if (status == 0) status = lcall(0, 0);
report(status);
if (status == 0 && lua_gettop(L) > 0) { /* any result to print? */
lua_getglobal(L, "print");
lua_insert(L, 1);
if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0)
l_message(progname, lua_pushfstring(L, "error calling `print' (%s)",
lua_tostring(L, -1)));
}
}
lua_settop(L, 0); /* clear stack */
fputs("\n", stdout);
progname = oldprogname;
}
static int handle_argv (char *argv[], int *interactive) {
if (argv[1] == NULL) { /* no more arguments? */
if (stdin_is_tty()) {
print_version();
manual_input();
}
else
file_input(NULL); /* executes stdin as a file */
}
else { /* other arguments; loop over them */
int i;
for (i = 1; argv[i] != NULL; i++) {
if (argv[i][0] != '-') break; /* not an option? */
switch (argv[i][1]) { /* option */
case '-': { /* `--' */
if (argv[i][2] != '\0') {
print_usage();
return 1;
}
i++; /* skip this argument */
goto endloop; /* stop handling arguments */
}
case '\0': {
file_input(NULL); /* executes stdin as a file */
break;
}
case 'i': {
*interactive = 1;
break;
}
case 'v': {
print_version();
break;
}
case 'e': {
const char *chunk = argv[i] + 2;
if (*chunk == '\0') chunk = argv[++i];
if (chunk == NULL) {
print_usage();
return 1;
}
if (dostring(chunk, "=<command line>") != 0)
return 1;
break;
}
case 'l': {
const char *filename = argv[i] + 2;
if (*filename == '\0') filename = argv[++i];
if (filename == NULL) {
print_usage();
return 1;
}
if (load_file(filename))
return 1; /* stop if file fails */
break;
}
case 'c': {
l_message(progname, "option `-c' is deprecated");
break;
}
case 's': {
l_message(progname, "option `-s' is deprecated");
break;
}
default: {
print_usage();
return 1;
}
}
} endloop:
if (argv[i] != NULL) {
const char *filename = argv[i];
getargs(argv, i); /* collect arguments */
lua_setglobal(L, "arg");
return file_input(filename); /* stop scanning arguments */
}
}
return 0;
}
static void openstdlibs (lua_State *l) {
const luaL_reg *lib = lualibs;
for (; lib->func; lib++) {
lib->func(l); /* open library */
lua_settop(l, 0); /* discard any results */
}
}
static int handle_luainit (void) {
const char *init = getenv("LUA_INIT");
if (init == NULL) return 0; /* status OK */
else if (init[0] == '@')
return file_input(init+1);
else
return dostring(init, "=LUA_INIT");
}
struct Smain {
int argc;
char **argv;
int status;
};
static int pmain (lua_State *l) {
struct Smain *s = (struct Smain *)lua_touserdata(l, 1);
int status;
int interactive = 0;
if (s->argv[0] && s->argv[0][0]) progname = s->argv[0];
L = l;
lua_userinit(l); /* open libraries */
status = handle_luainit();
if (status == 0) {
status = handle_argv(s->argv, &interactive);
if (status == 0 && interactive) manual_input();
}
s->status = status;
return 0;
}
int main (int argc, char *argv[]) {
int status;
struct Smain s;
lua_State *l = lua_open(); /* create state */
if (l == NULL) {
l_message(argv[0], "cannot create state: not enough memory");
return EXIT_FAILURE;
}
s.argc = argc;
s.argv = argv;
status = lua_cpcall(l, &pmain, &s);
report(status);
lua_close(l);
return (status || s.status) ? EXIT_FAILURE : EXIT_SUCCESS;
}

View file

@ -0,0 +1,18 @@
TOP = ../..
SWIG = $(TOP)/../swig
SRCS = example.c
TARGET = example
INTERFACE = example.i
all::
$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua
static::
$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static
clean::
$(MAKE) -f $(TOP)/Makefile lua_clean
check: all

View file

@ -0,0 +1,18 @@
/* File : example.c */
/* A global variable */
double Foo = 3.0;
/* Compute the greatest common divisor of positive integers */
int gcd(int x, int y) {
int g;
g = y;
while (x > 0) {
g = x;
x = y % x;
y = g;
}
return g;
}

View file

@ -0,0 +1,7 @@
/* File : example.i */
%module example
%inline %{
extern int gcd(int x, int y);
extern double Foo;
%}

View file

@ -0,0 +1,34 @@
-- file: runme.lua
-- importing (lua doesnt have a nice way to do this)
if example==nil then
assert(loadlib("example.dll","Example_Init"))()
end
-- Call our gcd() function
print("hello world")
x = 42
y = 105
g = example.gcd(x,y)
print("The gcd of",x,"and",y,"is",g)
-- Manipulate the Foo global variable
-- Output its current value
print("Foo = ", example.Foo)
-- Change its value
example.Foo = 3.1415926
-- See if the change took effect
print("Foo = ", example.Foo)

View file

@ -0,0 +1,18 @@
TOP = ../..
SWIG = $(TOP)/../swig
SRCS = example.c
TARGET = example
INTERFACE = example.i
all::
$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua
static::
$(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \
TARGET='mylua' INTERFACE='$(INTERFACE)' ;lua_static
clean::
$(MAKE) -f $(TOP)/Makefile lua_clean
check: all

View file

@ -0,0 +1,86 @@
/* File : example.c */
/* I'm a file containing some C global variables */
#include <stdio.h>
#include <stdlib.h>
#include "example.h"
int ivar = 0;
short svar = 0;
long lvar = 0;
unsigned int uivar = 0;
unsigned short usvar = 0;
unsigned long ulvar = 0;
signed char scvar = 0;
unsigned char ucvar = 0;
char cvar = 0;
float fvar = 0;
double dvar = 0;
char *strvar = 0;
const char cstrvar[] = "Goodbye";
int *iptrvar = 0;
char name[256] = "Dave";
char path[256] = "/home/beazley";
/* Global variables involving a structure */
Point *ptptr = 0;
Point pt = { 10, 20 };
/* A variable that we will make read-only in the interface */
int status = 1;
/* A debugging function to print out their values */
void print_vars() {
printf("ivar = %d\n", ivar);
printf("svar = %d\n", svar);
printf("lvar = %ld\n", lvar);
printf("uivar = %u\n", uivar);
printf("usvar = %u\n", usvar);
printf("ulvar = %lu\n", ulvar);
printf("scvar = %d\n", scvar);
printf("ucvar = %u\n", ucvar);
printf("fvar = %g\n", fvar);
printf("dvar = %g\n", dvar);
printf("cvar = %c\n", cvar);
printf("strvar = %s\n", strvar ? strvar : "(null)");
printf("cstrvar = %s\n", cstrvar ? cstrvar : "(null)");
printf("iptrvar = %p\n", iptrvar);
printf("name = %s\n", name);
printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0);
printf("pt = (%d, %d)\n", pt.x, pt.y);
printf("status = %d\n", status);
}
/* A function to create an integer (to test iptrvar) */
int *new_int(int value) {
int *ip = (int *) malloc(sizeof(int));
*ip = value;
return ip;
}
/* A function to create a point */
Point *new_Point(int x, int y) {
Point *p = (Point *) malloc(sizeof(Point));
p->x = x;
p->y = y;
return p;
}
char * Point_print(Point *p) {
static char buffer[256];
if (p) {
sprintf(buffer,"(%d,%d)", p->x,p->y);
} else {
sprintf(buffer,"null");
}
return buffer;
}
void pt_print() {
printf("(%d, %d)\n", pt.x, pt.y);
}

View file

@ -0,0 +1,6 @@
/* File: example.h */
typedef struct {
int x,y;
} Point;

View file

@ -0,0 +1,49 @@
/* File : example.i */
%module example
%{
#include "example.h"
%}
/* Some global variable declarations */
%inline %{
extern int ivar;
extern short svar;
extern long lvar;
extern unsigned int uivar;
extern unsigned short usvar;
extern unsigned long ulvar;
extern signed char scvar;
extern unsigned char ucvar;
extern char cvar;
extern float fvar;
extern double dvar;
extern char *strvar;
extern const char cstrvar[];
extern int *iptrvar;
extern char name[256];
extern Point *ptptr;
extern Point pt;
%}
/* Some read-only variables */
%immutable;
%inline %{
extern int status;
extern char path[256];
%}
%mutable;
/* Some helper functions to make it easier to test */
%inline %{
extern void print_vars();
extern int *new_int(int value);
extern Point *new_Point(int x, int y);
extern char *Point_print(Point *p);
extern void pt_print();
%}

View file

@ -0,0 +1,73 @@
-- file: example.lua
-- importing (lua doesnt have a nice way to do this)
if example==nil then
assert(loadlib("example.dll","Example_Init"))()
end
-- Try to set the values of some global variables
example.ivar = 42
example.svar = -31000
example.lvar = 65537
example.uivar = 123456
example.usvar = 61000
example.ulvar = 654321
example.scvar = -13
example.ucvar = 251
example.cvar = "S"
example.fvar = 3.14159
example.dvar = 2.1828
example.strvar = "Hello World"
example.iptrvar= example.new_int(37)
example.ptptr = example.new_Point(37,42)
example.name = "Bill"
-- Now print out the values of the variables
print("Variables (values printed from Lua)")
print("ivar =", example.ivar)
print("svar =", example.svar)
print("lvar =", example.lvar)
print("uivar =", example.uivar)
print("usvar =", example.usvar)
print("ulvar =", example.ulvar)
print("scvar =", example.scvar)
print("ucvar =", example.ucvar)
print("fvar =", example.fvar)
print("dvar =", example.dvar)
print("cvar =", example.cvar)
print("strvar =", example.strvar)
print("cstrvar =", example.cstrvar)
print("iptrvar =", example.iptrvar)
print("name =", example.name)
print("ptptr =", example.ptptr, example.Point_print(example.ptptr))
print("pt =", example.pt, example.Point_print(example.pt))
print("\nVariables (values printed from C)")
example.print_vars()
print "\nNow I'm going to try and modify some read only variables";
print " Tring to set 'path' to 'Whoa!'";
example.path = "Whoa!"
print " This request was silently ignored by Lua. "
print " But the data has not been changed"
print("path =", example.path)
print " Trying to set 'status' to '0'";
example.status = 0
print " Again silently ignored"
print("status =", example.status)
print "\nI'm going to try and update a structure variable.\n"
example.pt = example.ptptr
print "The new value is"
example.pt_print()
print("You should see the value", example.Point_print(example.ptptr))

View file

@ -0,0 +1,62 @@
#######################################################################
# $Header$
# Makefile for lua test-suite
#######################################################################
LANGUAGE = lua
LUA = @LUABIN@
SCRIPTSUFFIX = _runme.lua
srcdir = @srcdir@
top_srcdir = @top_srcdir@
top_builddir = @top_builddir@
# sorry, currently very few test cases work/have been written
#CPP_TEST_CASES += \
# cnum
#C_TEST_CASES += \
# file_test \
# nondynamic
include $(srcdir)/../common.mk
# Overridden variables here
LIBS = -L.
# Rules for the different types of tests
%.cpptest:
$(setup) \
($(swig_and_compile_cpp); ) &&\
$(run_testcase)
%.ctest:
$(setup) \
($(swig_and_compile_c); ) &&\
$(run_testcase)
%.multicpptest:
$(setup) \
($(swig_and_compile_multi_cpp); ) &&\
$(run_testcase)
# Runs the testcase. A testcase is only run if
# a file is found which has _runme.lua appended after the testcase name.
run_testcase = \
if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then ( \
$(LUA) $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX);) \
fi;
# Clean: (does nothing, we dont generate extra lua code)
%.clean:
clean:
$(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile lua_clean
cvsignore:
@echo '*wrap* *.so *.dll *.exp *.lib'
@echo Makefile
@for i in ${CPP_TEST_CASES} ${C_TEST_CASES}; do echo $$i.lua; done
@for i in ${CPP_TEST_CASES} ${C_TEST_CASES}; do if grep -q $${i}_runme.lua CVS/Entries ; then echo $${i}_runme.lua; fi; done

View file

@ -0,0 +1,17 @@
require("import") -- the import fn
import("abstract_access") -- import code
-- catch "undefined" global variables
setmetatable(getfenv(),{__index=function (t,i) error("undefined global variable `"..i.."'",2) end})
-- trying to instantiate pure virual classes
-- should fail
assert(pcall(abstract_access.A)==false)
assert(pcall(abstract_access.B)==false)
assert(pcall(abstract_access.C)==false)
-- instantiate object
d=abstract_access.D()
--call fn
assert(d:do_x()==1)

View file

@ -0,0 +1,20 @@
require("import") -- the import fn
import("enums",false) -- import lib
-- catch "undefined" global variables
setmetatable(getfenv(),{__index=function (t,i) error("undefined global variable `"..i.."'",2) end})
-- check values
assert(enums.CSP_ITERATION_FWD==0)
assert(enums.CSP_ITERATION_BWD==11)
assert(enums.ABCDE==0)
assert(enums.FGHJI==1)
assert(enums.boo==0)
assert(enums.hoo==5)
assert(enums.globalinstance1==0)
assert(enums.globalinstance2==1)
assert(enums.globalinstance3==30)
assert(enums.AnonEnum1==0)
assert(enums.AnonEnum2==100)
-- no point in checking fns, C will allow any value

View file

@ -0,0 +1,29 @@
-- demo of lua swig capacilities (operator overloading)
require("import") -- the import fn
import("exception_order",true) -- import lib into global
-- catching undefined variables
setmetatable(getfenv(),{__index=function (t,i) error("undefined global variable `"..i.."'",2) end})
a = A()
function try1()
a:foo()
end
ok,ex=pcall(try1)
assert(ok==false and swig_type(ex)==swig_type(E1()))
function try2()
a:bar()
end
ok,ex=pcall(try2)
assert(ok==false and swig_type(ex)==swig_type(E2()))
function try3()
a:foobar()
end
ok,ex=pcall(try3)
assert(ok==false and type(ex)=="string")
-- the SWIG_exception is just an error string

View file

@ -0,0 +1,25 @@
-- import
function import(module,intoglobal)
-- imports the file into the program
-- for a module example
-- this must load 'example.dll'
-- and look for the fn 'Example_Init()' (note the capitalisation)
local libname=module..".dll" -- windows
--libname=module..".so" -- unix
-- capitialising the first letter
local c=string.upper(string.sub(module,1,1))
local fnname=c..string.sub(module,2).."_Init"
assert(loadlib(libname,fnname),"error loading module:"..module)()
-- moving to global namespace
if intoglobal then
--m=raw_get(_G,module) -- gets the module object
local m=_G[module] -- gets the module object
assert(m~=nil,"no module table found")
local k,v
for k,v in m do _G[k]=v end
end
end

View file

@ -0,0 +1,16 @@
require("import") -- the import fn
import("newobject1",true) -- import code into global
foo1 = Foo_makeFoo() -- lua doesnt yet support static fns properly
assert(Foo_fooCount() == 1) -- lua doesnt yet support static fns properly
foo2 = foo1:makeMore()
assert(Foo_fooCount() == 2)
foo1 = nil
collectgarbage()
assert(Foo_fooCount() == 1)
foo2 = nil
collectgarbage()
assert(Foo_fooCount() == 0)

View file

@ -0,0 +1,16 @@
require("import") -- the import fn
import("newobject2",true) -- import code into global
foo1 = makeFoo() -- lua doesnt yet support static fns properly
assert(fooCount() == 1) -- lua doesnt yet support static fns properly
foo2 = makeFoo()
assert(fooCount() == 2)
foo1 = nil
collectgarbage()
assert(fooCount() == 1)
foo2 = nil
collectgarbage()
assert(fooCount() == 0)

View file

@ -0,0 +1,142 @@
-- demo of lua swig capacilities (operator overloading)
require("import") -- the import fn
import("operator_overload",true) -- import lib into global
-- catching undefined variables
setmetatable(getfenv(),{__index=function (t,i) error("undefined global variable `"..i.."'",2) end})
-- test routine:
a=Op()
b=Op(5)
c=Op(b) -- copy construct
d=Op(2)
-- test equality
assert(a~=b)
assert(b==c)
assert(a~=d)
-- test <
assert(a<b)
assert(a<=b)
assert(b<=c)
assert(b>=c)
assert(b>d)
assert(b>=d)
-- lua does not support += operators: skiping
-- test +
f=Op(1)
g=Op(1)
assert(f+g==Op(2))
assert(f-g==Op(0))
assert(f*g==Op(1))
assert(f/g==Op(1))
--assert(f%g==Op(0)) -- lua does not support %
-- test unary operators
--assert((not a)==true) -- lua does not allow overloading for not operator
--assert((not b)==false) -- lua does not allow overloading for not operator
assert(-a==a)
assert(-b==Op(-5))
-- test []
h=Op(3)
assert(h[0]==3)
assert(h[1]==0)
h[0]=2 -- set
assert(h[0]==2)
h[1]=2 -- ignored
assert(h[0]==2)
assert(h[1]==0)
-- test ()
i=Op(3)
assert(i()==3)
assert(i(1)==4)
assert(i(1,2)==6)
-- plus add some code to check the __str__ fn
assert(tostring(Op(1))=="Op(1)")
assert(tostring(Op(-3))=="Op(-3)")
--[[
/* Sample test code in C++
#include <assert.h>
#include <stdio.h>
int main(int argc,char** argv)
{
// test routine:
Op a;
Op b=5;
Op c=b; // copy construct
Op d=2;
// test equality
assert(a!=b);
assert(b==c);
assert(a!=d);
// test <
assert(a<b);
assert(a<=b);
assert(b<=c);
assert(b>=c);
assert(b>d);
assert(b>=d);
// test +=
Op e=3;
e+=d;
assert(e==b);
e-=c;
assert(e==a);
e=Op(1);
e*=b;
assert(e==c);
e/=d;
assert(e==d);
e%=c;
assert(e==d);
// test +
Op f(1),g(1);
assert(f+g==Op(2));
assert(f-g==Op(0));
assert(f*g==Op(1));
assert(f/g==Op(1));
assert(f%g==Op(0));
// test unary operators
assert(!a==true);
assert(!b==false);
assert(-a==a);
assert(-b==Op(-5));
// test []
Op h=3;
assert(h[0]==3);
assert(h[1]==0);
h[0]=2; // set
assert(h[0]==2);
h[1]=2; // ignored
assert(h[0]==2);
assert(h[1]==0);
// test ()
Op i=3;
assert(i()==3);
assert(i(1)==4);
assert(i(1,2)==6);
// plus add some code to check the __str__ fn
//assert(str(Op(1))=="Op(1)");
//assert(str(Op(-3))=="Op(-3)");
printf("ok\n");
}
*/
]]

View file

@ -0,0 +1,31 @@
require("import") -- the import fn
import("primitive_ref",true) -- import code into global namespace
assert(ref_int(3)==3)
assert(ref_uint(3) == 3)
assert(ref_short(3) == 3)
assert(ref_ushort(3) == 3)
assert(ref_long(3) == 3)
assert(ref_ulong(3) == 3)
assert(ref_schar(3) == 3)
assert(ref_uchar(3) == 3)
assert(ref_float(3.5) == 3.5)
assert(ref_double(3.5) == 3.5)
assert(ref_bool(true) == true)
assert(ref_char('x') == 'x')
assert(ref_over(0) == 0)
a=A(12)
assert(ref_over(a)==12)

View file

@ -0,0 +1,9 @@
require("import") -- the import fn
import("ret_by_value") -- import code
-- catch "undefined" global variables
setmetatable(getfenv(),{__index=function (t,i) error("undefined global variable `"..i.."'",2) end})
a = ret_by_value.get_test()
assert(a.myInt == 100)
assert(a.myShort == 200)