[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: embedded bytecode, was Re: extension for lua bytecode files
- From: Tony Finch <dot@...>
- Date: Sat, 16 Jun 2007 19:31:16 +0100
On Sat, 16 Jun 2007, Thomas Lauer wrote:
>
> This works very well. I have a 'shell' along the lines of lua.c which
> loads three or four byte-code libraries either from internal byte arrays
> or from external .lbc files.
I have been using a helper program to make this kind of array, but I would
have thought that it's a common enough requirement to build in to luac:
--- luac.c.orig Fri Jun 2 17:37:11 2006
+++ luac.c Sat Jun 16 18:26:12 2007
@@ -30,6 +30,7 @@
static int dumping=1; /* dump bytecodes? */
static int stripping=0; /* strip debug information? */
static char Output[]={ OUTPUT }; /* default output file name */
+static const char* Ccode; /* C wrapper name */
static const char* output=Output; /* actual output file name */
static const char* progname=PROGNAME; /* actual program name */
@@ -55,6 +56,7 @@
"usage: %s [options] [filenames].\n"
"Available options are:\n"
" - process stdin\n"
+ " -c name output C wrapper\n"
" -l list\n"
" -o name output to file " LUA_QL("name") " (default is \"%s\")\n"
" -p parse only\n"
@@ -84,6 +86,11 @@
}
else if (IS("-")) /* end of options; use stdin */
break;
+ else if (IS("-c")) /* output C wrapper */
+ {
+ Ccode=argv[++i];
+ if (Ccode==NULL || *Ccode==0) usage(LUA_QL("-c") " needs argument");
+ }
else if (IS("-l")) /* list */
++listing;
else if (IS("-o")) /* output file */
@@ -144,6 +151,33 @@
}
}
+static void Cprologue(FILE *D)
+{
+ fprintf(D,"/* auto-generated by luac */\n"
+ "void luaload_%s(lua_State *L) {\n"
+ " static const char bytecode[] = {\n ", Ccode);
+}
+
+static void Cepilogue(FILE *D)
+{
+ fprintf(D,"};\n if(luaL_loadbuffer(L,bytecode,sizeof(bytecode),"
+ "\"%s\"))\n lua_error(L);\n}\n", Ccode);
+}
+
+static int Cwriter(lua_State* L, const void* p, size_t size, void* u)
+{
+ UNUSED(L);
+ while (size > 0) {
+ if (fprintf((FILE*)u, "%d,", *(unsigned char *)p) < 0)
+ return 1;
+ p++; size--;
+ if (size % 20 == 0)
+ if (fprintf((FILE*)u, "\n ") < 0)
+ return 1;
+ }
+ return 0;
+}
+
static int writer(lua_State* L, const void* p, size_t size, void* u)
{
UNUSED(L);
@@ -174,9 +208,11 @@
{
FILE* D= (output==NULL) ? stdout : fopen(output,"wb");
if (D==NULL) cannot("open");
+ if (Ccode != NULL) Cprologue(D);
lua_lock(L);
- luaU_dump(L,f,writer,D,stripping);
+ luaU_dump(L,f, (Ccode != NULL) ? Cwriter : writer, D,stripping);
lua_unlock(L);
+ if (Ccode != NULL) Cepilogue(D);
if (ferror(D)) cannot("write");
if (fclose(D)) cannot("close");
}
Tony.
--
f.a.n.finch <dot@dotat.at> http://dotat.at/
FAEROES: NORTHEASTERLY 3 OR 4, INCREASING 5 OCCASIONALLY 6 LATER. SLIGHT OR
MODERATE. RAIN OR SHOWERS. MODERATE OR GOOD.