source: trunk/src/lua/loslib.c @ 2542

Last change on this file since 2542 was 2542, checked in by sam, 10 years ago

lua: compilation fixes for non-quite-POSIX platforms.

File size: 8.0 KB
Line 
1/*
2** $Id: loslib.c,v 1.39 2012/05/23 15:37:09 roberto Exp $
3** Standard Operating System library
4** See Copyright Notice in lua.h
5*/
6
7#if defined HAVE_CONFIG_H // LOL BEGIN
8#   include "config.h"
9#endif // LOL END
10
11#include <errno.h>
12#include <locale.h>
13#include <stdlib.h>
14#include <string.h>
15#include <time.h>
16
17#define loslib_c
18#define LUA_LIB
19
20#include "lua.h"
21
22#include "lauxlib.h"
23#include "lualib.h"
24
25
26/*
27** list of valid conversion specifiers for the 'strftime' function
28*/
29#if !defined(LUA_STRFTIMEOPTIONS)
30
31#if !defined(LUA_USE_POSIX)
32#define LUA_STRFTIMEOPTIONS     { "aAbBcdHIjmMpSUwWxXyYz%", "" }
33#else
34#define LUA_STRFTIMEOPTIONS \
35        { "aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%", "" \
36          "", "E", "cCxXyY",  \
37          "O", "deHImMSuUVwWy" }
38#endif
39
40#endif
41
42
43
44/*
45** By default, Lua uses tmpnam except when POSIX is available, where it
46** uses mkstemp.
47*/
48#if defined(LUA_USE_MKSTEMP)
49#include <unistd.h>
50#define LUA_TMPNAMBUFSIZE       32
51#define lua_tmpnam(b,e) { \
52        strcpy(b, "/tmp/lua_XXXXXX"); \
53        e = mkstemp(b); \
54        if (e != -1) close(e); \
55        e = (e == -1); }
56
57#elif !defined(lua_tmpnam)
58
59#define LUA_TMPNAMBUFSIZE       L_tmpnam
60#define lua_tmpnam(b,e)         { e = (tmpnam(b) == NULL); }
61
62#endif
63
64
65/*
66** By default, Lua uses gmtime/localtime, except when POSIX is available,
67** where it uses gmtime_r/localtime_r
68*/
69#if defined(LUA_USE_GMTIME_R)
70
71#define l_gmtime(t,r)           gmtime_r(t,r)
72#define l_localtime(t,r)        localtime_r(t,r)
73
74#elif !defined(l_gmtime)
75
76#define l_gmtime(t,r)           ((void)r, gmtime(t))
77#define l_localtime(t,r)        ((void)r, localtime(t))
78
79#endif
80
81
82
83static int os_execute (lua_State *L) {
84  const char *cmd = luaL_optstring(L, 1, NULL);
85  int stat = system(cmd);
86  if (cmd != NULL)
87    return luaL_execresult(L, stat);
88  else {
89    lua_pushboolean(L, stat);  /* true if there is a shell */
90    return 1;
91  }
92}
93
94
95static int os_remove (lua_State *L) {
96  const char *filename = luaL_checkstring(L, 1);
97  return luaL_fileresult(L, remove(filename) == 0, filename);
98}
99
100
101static int os_rename (lua_State *L) {
102  const char *fromname = luaL_checkstring(L, 1);
103  const char *toname = luaL_checkstring(L, 2);
104  return luaL_fileresult(L, rename(fromname, toname) == 0, fromname);
105}
106
107
108static int os_tmpname (lua_State *L) {
109  char buff[LUA_TMPNAMBUFSIZE];
110  int err;
111  lua_tmpnam(buff, err);
112  if (err)
113    return luaL_error(L, "unable to generate a unique filename");
114  lua_pushstring(L, buff);
115  return 1;
116}
117
118
119static int os_getenv (lua_State *L) {
120#if HAVE_GETENV // LOL BEGIN
121  lua_pushstring(L, getenv(luaL_checkstring(L, 1)));  /* if NULL push nil */
122#else
123  lua_pushstring(L, NULL);
124#endif // LOL END
125  return 1;
126}
127
128
129static int os_clock (lua_State *L) {
130  lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC);
131  return 1;
132}
133
134
135/*
136** {======================================================
137** Time/Date operations
138** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S,
139**   wday=%w+1, yday=%j, isdst=? }
140** =======================================================
141*/
142
143static void setfield (lua_State *L, const char *key, int value) {
144  lua_pushinteger(L, value);
145  lua_setfield(L, -2, key);
146}
147
148static void setboolfield (lua_State *L, const char *key, int value) {
149  if (value < 0)  /* undefined? */
150    return;  /* does not set field */
151  lua_pushboolean(L, value);
152  lua_setfield(L, -2, key);
153}
154
155static int getboolfield (lua_State *L, const char *key) {
156  int res;
157  lua_getfield(L, -1, key);
158  res = lua_isnil(L, -1) ? -1 : lua_toboolean(L, -1);
159  lua_pop(L, 1);
160  return res;
161}
162
163
164static int getfield (lua_State *L, const char *key, int d) {
165  int res, isnum;
166  lua_getfield(L, -1, key);
167  res = (int)lua_tointegerx(L, -1, &isnum);
168  if (!isnum) {
169    if (d < 0)
170      return luaL_error(L, "field " LUA_QS " missing in date table", key);
171    res = d;
172  }
173  lua_pop(L, 1);
174  return res;
175}
176
177
178static const char *checkoption (lua_State *L, const char *conv, char *buff) {
179  static const char *const options[] = LUA_STRFTIMEOPTIONS;
180  unsigned int i;
181  for (i = 0; i < sizeof(options)/sizeof(options[0]); i += 2) {
182    if (*conv != '\0' && strchr(options[i], *conv) != NULL) {
183      buff[1] = *conv;
184      if (*options[i + 1] == '\0') {  /* one-char conversion specifier? */
185        buff[2] = '\0';  /* end buffer */
186        return conv + 1;
187      }
188      else if (*(conv + 1) != '\0' &&
189               strchr(options[i + 1], *(conv + 1)) != NULL) {
190        buff[2] = *(conv + 1);  /* valid two-char conversion specifier */
191        buff[3] = '\0';  /* end buffer */
192        return conv + 2;
193      }
194    }
195  }
196  luaL_argerror(L, 1,
197    lua_pushfstring(L, "invalid conversion specifier '%%%s'", conv));
198  return conv;  /* to avoid warnings */
199}
200
201
202static int os_date (lua_State *L) {
203  const char *s = luaL_optstring(L, 1, "%c");
204  time_t t = luaL_opt(L, (time_t)luaL_checknumber, 2, time(NULL));
205  struct tm tmr, *stm;
206  if (*s == '!') {  /* UTC? */
207    stm = l_gmtime(&t, &tmr);
208    s++;  /* skip `!' */
209  }
210  else
211    stm = l_localtime(&t, &tmr);
212  if (stm == NULL)  /* invalid date? */
213    lua_pushnil(L);
214  else if (strcmp(s, "*t") == 0) {
215    lua_createtable(L, 0, 9);  /* 9 = number of fields */
216    setfield(L, "sec", stm->tm_sec);
217    setfield(L, "min", stm->tm_min);
218    setfield(L, "hour", stm->tm_hour);
219    setfield(L, "day", stm->tm_mday);
220    setfield(L, "month", stm->tm_mon+1);
221    setfield(L, "year", stm->tm_year+1900);
222    setfield(L, "wday", stm->tm_wday+1);
223    setfield(L, "yday", stm->tm_yday+1);
224    setboolfield(L, "isdst", stm->tm_isdst);
225  }
226  else {
227    char cc[4];
228    luaL_Buffer b;
229    cc[0] = '%';
230    luaL_buffinit(L, &b);
231    while (*s) {
232      if (*s != '%')  /* no conversion specifier? */
233        luaL_addchar(&b, *s++);
234      else {
235        size_t reslen;
236        char buff[200];  /* should be big enough for any conversion result */
237        s = checkoption(L, s + 1, cc);
238        reslen = strftime(buff, sizeof(buff), cc, stm);
239        luaL_addlstring(&b, buff, reslen);
240      }
241    }
242    luaL_pushresult(&b);
243  }
244  return 1;
245}
246
247
248static int os_time (lua_State *L) {
249  time_t t;
250  if (lua_isnoneornil(L, 1))  /* called without args? */
251    t = time(NULL);  /* get current time */
252  else {
253    struct tm ts;
254    luaL_checktype(L, 1, LUA_TTABLE);
255    lua_settop(L, 1);  /* make sure table is at the top */
256    ts.tm_sec = getfield(L, "sec", 0);
257    ts.tm_min = getfield(L, "min", 0);
258    ts.tm_hour = getfield(L, "hour", 12);
259    ts.tm_mday = getfield(L, "day", -1);
260    ts.tm_mon = getfield(L, "month", -1) - 1;
261    ts.tm_year = getfield(L, "year", -1) - 1900;
262    ts.tm_isdst = getboolfield(L, "isdst");
263    t = mktime(&ts);
264  }
265  if (t == (time_t)(-1))
266    lua_pushnil(L);
267  else
268    lua_pushnumber(L, (lua_Number)t);
269  return 1;
270}
271
272
273static int os_difftime (lua_State *L) {
274  lua_pushnumber(L, difftime((time_t)(luaL_checknumber(L, 1)),
275                             (time_t)(luaL_optnumber(L, 2, 0))));
276  return 1;
277}
278
279/* }====================================================== */
280
281
282static int os_setlocale (lua_State *L) {
283  static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY,
284                      LC_NUMERIC, LC_TIME};
285  static const char *const catnames[] = {"all", "collate", "ctype", "monetary",
286     "numeric", "time", NULL};
287  const char *l = luaL_optstring(L, 1, NULL);
288  int op = luaL_checkoption(L, 2, "all", catnames);
289  lua_pushstring(L, setlocale(cat[op], l));
290  return 1;
291}
292
293
294static int os_exit (lua_State *L) {
295  int status;
296  if (lua_isboolean(L, 1))
297    status = (lua_toboolean(L, 1) ? EXIT_SUCCESS : EXIT_FAILURE);
298  else
299    status = luaL_optint(L, 1, EXIT_SUCCESS);
300  if (lua_toboolean(L, 2))
301    lua_close(L);
302  if (L) exit(status);  /* 'if' to avoid warnings for unreachable 'return' */
303  return 0;
304}
305
306
307static const luaL_Reg syslib[] = {
308  {"clock",     os_clock},
309  {"date",      os_date},
310  {"difftime",  os_difftime},
311  {"execute",   os_execute},
312  {"exit",      os_exit},
313  {"getenv",    os_getenv},
314  {"remove",    os_remove},
315  {"rename",    os_rename},
316  {"setlocale", os_setlocale},
317  {"time",      os_time},
318  {"tmpname",   os_tmpname},
319  {NULL, NULL}
320};
321
322/* }====================================================== */
323
324
325
326LUAMOD_API int luaopen_os (lua_State *L) {
327  luaL_newlib(L, syslib);
328  return 1;
329}
330
Note: See TracBrowser for help on using the repository browser.