Imported from ../lua-1.0.tar.gz.
[lua.git] / strlib.c
blobefd01e9b233db98e30a95c3b85edf701531e2599
1 /*
2 ** strlib.c
3 ** String library to LUA
4 **
5 ** Waldemar Celes Filho
6 ** TeCGraf - PUC-Rio
7 ** 19 May 93
8 */
10 #include <stdlib.h>
11 #include <string.h>
12 #include <ctype.h>
15 #include "lua.h"
18 ** Return the position of the first caracter of a substring into a string
19 ** LUA interface:
20 ** n = strfind (string, substring)
22 static void str_find (void)
24 int n;
25 char *s1, *s2;
26 lua_Object o1 = lua_getparam (1);
27 lua_Object o2 = lua_getparam (2);
28 if (!lua_isstring(o1) || !lua_isstring(o2))
29 { lua_error ("incorrect arguments to function `strfind'"); return; }
30 s1 = lua_getstring(o1);
31 s2 = lua_getstring(o2);
32 n = strstr(s1,s2) - s1 + 1;
33 lua_pushnumber (n);
37 ** Return the string length
38 ** LUA interface:
39 ** n = strlen (string)
41 static void str_len (void)
43 lua_Object o = lua_getparam (1);
44 if (!lua_isstring(o))
45 { lua_error ("incorrect arguments to function `strlen'"); return; }
46 lua_pushnumber(strlen(lua_getstring(o)));
51 ** Return the substring of a string, from start to end
52 ** LUA interface:
53 ** substring = strsub (string, start, end)
55 static void str_sub (void)
57 int start, end;
58 char *s;
59 lua_Object o1 = lua_getparam (1);
60 lua_Object o2 = lua_getparam (2);
61 lua_Object o3 = lua_getparam (3);
62 if (!lua_isstring(o1) || !lua_isnumber(o2) || !lua_isnumber(o3))
63 { lua_error ("incorrect arguments to function `strsub'"); return; }
64 s = strdup (lua_getstring(o1));
65 start = lua_getnumber (o2);
66 end = lua_getnumber (o3);
67 if (end < start || start < 1 || end > strlen(s))
68 lua_pushstring ("");
69 else
71 s[end] = 0;
72 lua_pushstring (&s[start-1]);
74 free (s);
78 ** Convert a string to lower case.
79 ** LUA interface:
80 ** lowercase = strlower (string)
82 static void str_lower (void)
84 char *s, *c;
85 lua_Object o = lua_getparam (1);
86 if (!lua_isstring(o))
87 { lua_error ("incorrect arguments to function `strlower'"); return; }
88 c = s = strdup(lua_getstring(o));
89 while (*c != 0)
91 *c = tolower(*c);
92 c++;
94 lua_pushstring(s);
95 free(s);
100 ** Convert a string to upper case.
101 ** LUA interface:
102 ** uppercase = strupper (string)
104 static void str_upper (void)
106 char *s, *c;
107 lua_Object o = lua_getparam (1);
108 if (!lua_isstring(o))
109 { lua_error ("incorrect arguments to function `strlower'"); return; }
110 c = s = strdup(lua_getstring(o));
111 while (*c != 0)
113 *c = toupper(*c);
114 c++;
116 lua_pushstring(s);
117 free(s);
122 ** Open string library
124 void strlib_open (void)
126 lua_register ("strfind", str_find);
127 lua_register ("strlen", str_len);
128 lua_register ("strsub", str_sub);
129 lua_register ("strlower", str_lower);
130 lua_register ("strupper", str_upper);