1 /* tolua: error handling
2 ** Support code for Lua bindings.
3 ** Written by Waldemar Celes
4 ** TeCGraf/PUC-Rio
5 ** Jul 1998
6 ** $Id$
7 */
8
9 /* This code is free software; you can redistribute it and/or modify it.
10 ** The software provided hereunder is on an "as is" basis, and
11 ** the author has no obligation to provide maintenance, support, updates,
12 ** enhancements, or modifications.
13 */
14
15 #include "tolua.h"
16 #include "tolua_eh.h"
17 #include "tolua_rg.h"
18
19 #include <stdio.h>
20
21 /* registry fiels used to hold current error info
22 - tolua_err_narg: number of wrong argument
23 - tolua_err_provided: provided type
24 - tolua_err_expected: expected type
25 */
26
toluaI_eh_set(lua_State * L,int narg,const char * provided,const char * expected)27 void toluaI_eh_set
28 (lua_State* L, int narg, const char* provided, const char* expected)
29 {
30 lua_pushnumber(L,narg);
31 toluaI_setregistry(L,"tolua_err_narg");
32 lua_pushstring(L,provided);
33 toluaI_setregistry(L,"tolua_err_provided");
34 lua_pushstring(L,expected);
35 toluaI_setregistry(L,"tolua_err_expected");
36 }
37
tolua_error(lua_State * L,char * msg)38 void tolua_error (lua_State* L, char* msg)
39 {
40 if (msg[0]=='#')
41 {
42 static char buffer[BUFSIZ];
43 const char* err_provided;
44 const char* err_expected;
45 toluaI_getregistry(L,"tolua_err_provided");
46 err_provided = lua_tostring(L,-1);
47 toluaI_getregistry(L,"tolua_err_expected");
48 err_expected = lua_tostring(L,-1);
49 lua_pop(L,2);
50 if (msg[1]=='f')
51 {
52 int err_narg;
53 toluaI_getregistry(L,"tolua_err_narg");
54 err_narg = (int)lua_tonumber(L,-1);
55 lua_pop(L,1);
56 sprintf(buffer,"%s\n argument #%d is '%s'; '%s' expected.\n",
57 msg+2,err_narg,err_provided,err_expected);
58 }
59 else if (msg[1]=='v')
60 sprintf(buffer,"%s\n value is '%s'; '%s' expected.\n",
61 msg+2,err_provided,err_expected);
62 lua_error(L,buffer);
63 }
64 else
65 lua_error(L,msg);
66 }
67