2 * LuCI Core - Utility library
3 * Copyright (C) 2008 Steven Barth <steven@midlink.org>
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
20 #define LUCI_MODNAME "luci.cutil"
21 #define LUCI_MODDESC "LuCI Core Utility Library"
22 #define LUCI_MODCOPY "2008 Steven Barth"
25 /* Pythonic overloaded MOD operator */
26 static int luci__string_mod(lua_State *L) {
29 luaL_checkstring(L, 1);
32 /* Discard further arguments */
35 /* Get format and push it to the bottom of the stack */
36 lua_pushliteral(L, "");
37 lua_getfield(L, -1, "format");
41 /* If second argument is a table, unpack it */
42 if (lua_istable(L, 3)) {
45 luaL_checkstack(L, n, "too many results to unpack");
46 for (i=1; i<=n; i++) {
59 /* Instantiate a class */
60 static int luci__instantiate(lua_State *L) {
61 luaL_checktype(L, 1, LUA_TTABLE);
63 /* Create the object */
66 /* Create the metatable */
67 lua_createtable(L, 0, 1);
69 lua_setfield(L, -2, "__index");
70 lua_setmetatable(L, -2);
72 /* Move instance at the bottom of the stack */
75 /* Invoke constructor if it exists */
76 lua_getfield(L, 1, "__init__");
77 if (lua_isfunction(L, -1)) {
78 /* Put instance at the bottom for the 2nd time */
82 /* Call constructor */
84 lua_call(L, lua_gettop(L)-2, 0);
92 /* luci.cutil.class(baseclass) */
93 static int luci_class(lua_State *L) {
97 /* Create metatable and register parent class if any */
98 if (lua_istable(L, 1)) {
99 lua_createtable(L, 0, 2);
101 lua_setfield(L, -2, "__index");
103 lua_createtable(L, 0, 1);
106 /* Set instantiator */
107 lua_pushcfunction(L, luci__instantiate);
108 lua_setfield(L, -2, "__call");
110 lua_setmetatable(L, -2);
116 static const luaL_Reg registry[] = {
117 {"class", luci_class},
122 LUALIB_API int luaopen_luci_cutil(lua_State *L) {
123 luaL_register(L, LUCI_MODNAME, registry);
125 lua_pushliteral(L, LUCI_MODDESC);
126 lua_setfield(L, -2, "_DESCRIPTION");
128 lua_pushliteral(L, LUCI_MODCOPY);
129 lua_setfield(L, -2, "_COPYRIGHT");
132 /* Register pythonic printf string operator */
133 lua_pushliteral(L, "");
134 lua_getmetatable(L, -1);
135 lua_pushcfunction(L, luci__string_mod);
136 lua_setfield(L, -2, "__mod");