aboutsummaryrefslogtreecommitdiff
path: root/src/misc.c
blob: 2bea4c813a93d945d1c5a5fbdc18d76620a8c8c6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
 * LSPIPAT - LUA SPIPAT WRAPPER
 * Copyright (C) 2010, Robin Haberkorn
 * License: LGPL
 *
 * CORE: MISCELLANEOUS PRIMITIVES/CONSTRUCTORS
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <string.h>

#include "lspipat.h"

LUA_SIG(l_primitive_arbno)
{
	int top = lua_gettop(L);

	VString		str = VSTRING_INITIALIZER;
	PATTERN_WRAPPER	*new;

	luaL_argcheck(L, top == 1, top, L_NUMBER);

	if (!(new = lua_newuserdata(L, sizeof(PATTERN_WRAPPER))))
		L_ERROR(L_ALLOC);
	memset(new, 0, sizeof(PATTERN_WRAPPER));

	if (lua_isstring(L, 1)) {
		str.ptr = lua_tolstring(L, 1, (size_t *)&str.len);

		new->pattern = str.len == 1 ? spipat_arbno_chr(*str.ptr)
					    : spipat_arbno_str(str);
	} else {
		PATTERN_WRAPPER *wrapper = luaL_checkudata(L, 1, PATTERN_MT);
		luaL_argcheck(L, wrapper->pattern, 1, L_FREED);

		lua_insert(L, 1);		/* move wrapper to bottom */
		new->type = PATTERN_ONESUBPAT;
		new->u.onesubpat.pattern = luaL_ref(L, LUA_REGISTRYINDEX);
						/* wrapper at top again */

		new->pattern = spipat_arbno(wrapper->pattern);
	}

	if (!new->pattern)
		L_ERROR(L_ALLOC);

	luaL_getmetatable(L, PATTERN_MT);
	lua_setmetatable(L, -2);

	return 1;

}

LUA_SIG(l_primitive_fence)
{
	int top = lua_gettop(L);
	PATTERN_WRAPPER *new;

	luaL_argcheck(L, top < 2, top, L_NUMBER);

	if (!(new = lua_newuserdata(L, sizeof(PATTERN_WRAPPER))))
		L_ERROR(L_ALLOC);
	memset(new, 0, sizeof(PATTERN_WRAPPER));

	if (!top) {
		new->pattern = spipat_fence_simple();
	} else {
		PATTERN_WRAPPER *wrapper = luaL_checkudata(L, 1, PATTERN_MT);
		luaL_argcheck(L, wrapper->pattern, 1, L_FREED);

		lua_insert(L, 1);		/* move wrapper to bottom */
		new->type = PATTERN_ONESUBPAT;
		new->u.onesubpat.pattern = luaL_ref(L, LUA_REGISTRYINDEX);
						/* wrapper at top again */

		new->pattern = spipat_fence_function(wrapper->pattern);
	}

	if (!new->pattern)
		L_ERROR(L_ALLOC);

	luaL_getmetatable(L, PATTERN_MT);
	lua_setmetatable(L, -2);

	return 1;
}