summaryrefslogtreecommitdiff
path: root/worldedit/code.lua
blob: fb04ce9bb9c6e615f4207ef642443bd9ef5ea3a7 (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
worldedit = worldedit or {}
local minetest = minetest --local copy of global

--modifies positions `pos1` and `pos2` so that each component of `pos1` is less than or equal to its corresponding conent of `pos2`, returning two new positions
worldedit.sort_pos = function(pos1, pos2)
	pos1 = {x=pos1.x, y=pos1.y, z=pos1.z}
	pos2 = {x=pos2.x, y=pos2.y, z=pos2.z}
	if pos1.x > pos2.x then
		pos2.x, pos1.x = pos1.x, pos2.x
	end
	if pos1.y > pos2.y then
		pos2.y, pos1.y = pos1.y, pos2.y
	end
	if pos1.z > pos2.z then
		pos2.z, pos1.z = pos1.z, pos2.z
	end
	return pos1, pos2
end

--executes `code` as a Lua chunk in the global namespace, returning an error if the code fails or nil otherwise
worldedit.lua = function(code)
	local operation, message = loadstring(code)
	if operation == nil then --code parsing failed
		return message
	end
	local status, message = pcall(operation)
	if status == nil then --operation failed
		return message
	end
	return nil
end

--executes `code` as a Lua chunk in the global namespace with the variable pos available, for each node in a region defined by positions `pos1` and `pos2`, returning an error if the code fails or nil otherwise
worldedit.luatransform = function(pos1, pos2, code)
	local pos1, pos2 = worldedit.sort_pos(pos1, pos2)

	local factory, message = loadstring("return function(pos) " .. code .. " end")
	if factory == nil then --code parsing failed
		return message
	end
	local operation = factory()

	--make area stay loaded
	local manip = minetest.get_voxel_manip()
	manip:read_from_map(pos1, pos2)

	local pos = {x=pos1.x, y=0, z=0}
	while pos.x <= pos2.x do
		pos.y = pos1.y
		while pos.y <= pos2.y do
			pos.z = pos1.z
			while pos.z <= pos2.z do
				local status, message = pcall(operation, pos)
				if status == nil then --operation failed
					return message
				end
				pos.z = pos.z + 1
			end
			pos.y = pos.y + 1
		end
		pos.x = pos.x + 1
	end
	return nil
end