-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample.bit
83 lines (71 loc) · 2.6 KB
/
example.bit
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
package:application/vnd.bitty-archive;
data:text/lua;count=1632;path=bf/compiler.lua;
--[[
BF compiler for the Bitty Engine
Copyright (C) 2020 - 2021 Tony Wang, all rights reserved
Homepage: https://paladin-t.github.io/bitty/
]]
-- Based on https://github.com/prapin/LuaBrainFuck.
local interpreter = 'local output = \'\'\n' ..
'local input_ = function()\n' ..
' local i = input()\n' ..
' return i and i:byte(1) or 0\n' ..
'end\n' ..
'local function interpret(s)\n' ..
' local subst = {["+"]="v=v+1 ", ["-"]="v=v-1 ", [">"]="i=i+1 ", ["<"]="i=i-1 ",\n' ..
' ["."] = "w(v)", [","]="v=r()", ["["]="while v~=0 do ", ["]"]="end "}\n' ..
' local env = setmetatable({ i=0, t=setmetatable({},{__index=function() return 0 end}),\n' ..
' r=function() return input_() end, w=function(c) output=output..string.char(c) end },\n' ..
' {__index=function(t,k) return t.t[t.i] end, __newindex=function(t,k,v) t.t[t.i]=v end })\n' ..
' load(s:gsub("[^%+%-<>%.,%[%]]+",""):gsub(".", subst), "brainfuck", "t", env)()\n' ..
' print(output)\n' ..
'end\n'
-- Compiles from an asset.
function compile(asset)
if not asset then
error('Invalid asset.')
end
local bytes = Project.main:read(asset)
if not bytes then
error('Invalid asset.')
end
bytes:poke(1)
local src = bytes:readString()
local dst = ''
for ln in src:gmatch('([^\n]*)\n?') do
if #ln > 0 then
local comment = ln:find('#')
if comment then
ln = ln:sub(1, comment - 1) -- Remove comment.
end
dst = dst .. ln -- Concat lines.
end
end
local full = interpreter .. 'interpret(\'' .. dst .. '\')' -- Link the source code with the interpreter together.
return load(full) -- Return loaded and parsed Lua chunk.
end
data:text/txt;count=96;path=bf/README.txt;
# BF compiler for Bitty Engine
Usage:
require 'bf/compiler'
f = compile('source.bf')
f()
data:binary/octet;count=231;path=hello world.bf;
++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.++ # The BF compiler supports new lines,
+.------.--------.>+.>. # and comments.
data:text/json;count=206;path=info.json;
{
"id": 0,
"title": "BF Example",
"description": "A BF example project.",
"author": "Tony",
"version": "1.0",
"genre": "TUTORIAL",
"url": "https://github.com/paladin-t/bitty.compiler_plugin"
}
data:binary/octet;count=6;path=input.bf;
,.,.,.
data:text/lua;count=183;path=main.lua;
require 'bf/compiler' -- Require the compiler.
local f = compile('hello world.bf') -- Compile something.
f() -- Run the compiled chunk.