def attr_getter(obj, attr_name): allowed_attr = ['method', 'path', 'query', 'form'] if attr_name in allowed_attr: return getattr(obj, attr_name) raise AttributeError('not allowed to read %s' % attr_name) def attr_setter(obj, attr_name): raise AttributeError('not allowed to write') class Request(object): def __init__(self): self.path = '/' self.method = 'GET' self.query = {} self.form = {} request = Request() CWD = os.path.abspath(os.path.dirname(__file__)) lua = LuaRuntime(unpack_returned_tuples=True, attribute_handlers=(attr_getter, attr_setter)) sandbox = lua.eval("require('sandbox')") #sandbox["allowed_require_names"] = python2lua( # lua, # {name: True for name in [request]} #) lua_script = open(os.path.join(CWD, 'test.lua')).read() result = sandbox.run('function main(request) ' + lua_script + ' end') print result print sandbox.env["main"](request)
def load_lua(path): with open(path, encoding='utf-8') as f: s = f.read() s = re.sub('Vector3\((.*?)\)', '{\g<1>}', s) s = re.sub('AspectMode\.[A-Za-z]+', '"\g<0>"', s) lua = LuaRuntime(unpack_returned_tuples=True) return convert_lua_to_python_dict(lua.execute(s))
class LuaProcessor(ComputableInputProcessor): def __init__(self): self.lua = LuaRuntime() self.lua.execute(_LUA_HELPERS) def check_funct(self, funct, computable_type): # dummy insert function start / end if not funct.startswith('function') \ and not funct.endswith('end'): if computable_type == ComputablePassedTypes.full.name: make_arr = 'local R = make_arr(D)' funct = "%s\n%s" % (make_arr, funct) return 'function (D, resource_name) %s end' % funct return funct def run(self, resource_name, computable_type, funct, data): # when computable_type == full then raw python object is passed # to lua (counts from 0 etc) if isinstance(data, list) \ and computable_type == ComputablePassedTypes.values.name: lua_data = self.lua.table_from(data) else: lua_data = data funct = self.check_funct(funct, computable_type) funct_lua = self.lua.eval(funct) return funct_lua(lua_data, resource_name)
def exec_lua(code: str): # the attribute_handlers are probably enough to prevent access eval otherwise lua = LuaRuntime(register_eval=False, unpack_returned_tuples=True, attribute_handlers=(getter, setter)) # execute the sandbox preamble sandbox = lua.execute(sandbox_preamble) # call sandbox.run with `glob.sandbox, code` # and unpack the variables _ = sandbox.run(code, lua.table_from({})) if isinstance(_, bool): # idk return NO_RESULT called, result = _ if lupa.lua_type(result) == 'table': # dictify result = dictify_table_recursively(result) try: pickle.dumps(result) except: return str(result) return result
def __load(self): self.lua = LuaRuntime(unpack_returned_tuples=True, register_eval=False, attribute_handlers=(self.__getter, self.__setter)) setattr(self.lua.globals(), 'print', self.p) # Remove potentially dangerous functions self.__sandboxInterpreter() # Install a sleep function as lua script since it need to be able to yield self.lua.execute( 'function sleep(ms)\nif suspend(ms) then\ncoroutine.yield()\nend\nend' ) setattr(self.lua.globals(), 'suspend', self.__luaSleep) try: self.lua.execute(self.code) # Register which signals the script accepts so we don't need to access # the interpreter from any other thread. That leads to locks. self.__allowedSignals = [] for func in self.lua.globals(): self.__allowedSignals.append(func) self.__setState(LuaScript.IDLE) # Allow script to initialize itself self.call('onInit') self.p("Script %s loaded", self.name) except Exception as e: self.__setState(LuaScript.ERROR) self.p("Could not load lua script %s: %s", self.name, e)
def main(): with open('test.lua') as f: lua_code = f.read() non_explode_lua = LuaRuntime(unpack_returned_tuples=False) non_explode_lua.execute(lua_code) g = non_explode_lua.globals() print(g.run(55))
def initialize_lua(ctx): def filter_attribute_access(obj, attr_name, is_setting): if isinstance(attr_name, unicode): if not attr_name.startswith("_"): return attr_name raise AttributeError("access denied") lua = LuaRuntime(unpack_returned_tuples=True, register_eval=False, attribute_filter=filter_attribute_access) ctx.lua = lua # Load Lua sandbox Phase 1. This is a very minimal file that only sets # the Lua loader to our custom loader; we will then use it to load the # bigger phase 2 of the sandbox. This way, most of the sandbox loading # will benefit from caching and precompilation (when implemented). lua_sandbox = open(lua_dir + "_sandbox_phase1.lua", encoding="utf-8").read() set_loader = lua.execute(lua_sandbox) # Call the function that sets the Lua loader set_loader(lambda x: lua_loader(ctx, x)) # Then load the second phase of the sandbox. This now goes through the # new loader and is evaluated in the sandbox. This mostly implements # compatibility code. ret = lua.eval('new_require("_sandbox_phase2")') set_functions = ret[1] ctx.lua_invoke = ret[2] ctx.lua_reset_env = ret[3] # Set Python functions for Lua call_set_functions(ctx, set_functions)
def get_label_for_problem(self): if not self.problem_label_script: return self.format.get_label_for_problem def DENY_ALL(obj, attr_name, is_setting): raise AttributeError() lua = LuaRuntime(attribute_filter=DENY_ALL, register_eval=False, register_builtins=False) return lua.eval(self.problem_label_script)
def LoadLua(filepath): if type(filepath) == type(""): filepath = Path(filepath) lua = LuaRuntime(unpack_returned_tuples=True) lua_code = filepath.read_bytes().decode('utf-8') unit = lua.execute(lua_code) return ExpandTable(unit)
def __init__(self, name, *args, **kwargs): super(ObjectWrapper, self).__init__(*args, **kwargs) rsrc = ObjectResource().load(name) self.instance = ObjectInstance(name, rsrc[0], rsrc[1]) self.lua = LuaRuntime() self.lua.execute(rsrc[2])
def query(cls, queries, doc, **kwargs): result = [] for query in queries: lua = LuaRuntime(unpack_returned_tuples=False) handle_func = lua.eval(query) ret = handle_func(lupa.as_attrgetter(doc), kwargs) result.extend(ret) return result
class TestLuaCheckInstall(unittest.TestCase): def setUp(self): self.lua = LuaRuntime() def test_luajit(self): self.assertFalse(self.lua.eval('jit == nil')) def test_luajit2(self): self.assertTrue(self.lua.eval('jit.status()')[0])
def group_reduce(input_data, script): import lupa from lupa import LuaRuntime lua = LuaRuntime(unpack_returned_tuples=False) g = lua.globals() g.input = input_data g._count = _count output = lua.eval(script) return output
def save_to_file(json_data, path, name, prop_table): lua = LuaRuntime() lua.require("serialize_json") if name in prop_table: func = lua.eval('''function(json_data, path, name) save_to_file_prop(json_data, path, name); end''') func(json_data, path, name) else: func = lua.eval('''function(json_data, path, name) save_to_file(json_data, path, name); end''') func(json_data, path, name)
def __init__(self) -> None: """Create a Lua runtime and set up the sandbox environment inside it.""" self.lua = LuaRuntime( register_eval=False, register_builtins=False, unpack_returned_tuples=True, attribute_handlers=(getter_handler, setter_handler), ) self.lua.execute(f"package.path = '{LUA_PACKAGES_PATH}'") self.sandbox = self.lua.eval('require("sandbox")')
def parse_modinfo_string(content: str): lua = LuaRuntime(unpack_returned_tuples=True) lua.execute(content) g = lua.globals() name = g.name configs = [] if g.configuration_options: configs_lua = g.configuration_options.values() configs = ModInfoConfig.load_from_configs_lua(configs_lua) return ModInfo(name, OrderedDict(map(lambda x: (x.name, x), configs)))
def __init__(self, source, name, parent): """Throws LuaExceptions (LuaError or LuaSyntaxError)""" self.name = name self.source = source self.vapor_client = VaporClient() self.get_led_data = self.vapor_client.get_led_data self.runtime = LuaRuntime() self.render_function = None self.render_function = self.runtime.eval(source) if self.render_function is None: print "no render callback!"
def load_lua(): global fd_time_boot lua = LuaRuntime(unpack_returned_tuples=True) statinfo = os.stat('handle.lua') fd_time_boot = statinfo.st_mtime _ = lua.require('handle') yep = lua.eval(''' function(i, time) return handle_cmd(i, time) end ''') return yep, lua
def index(request): i_request = Request(request) lua = LuaRuntime(unpack_returned_tuples=True) lua.execute('package.path = "%s/?.lua;" .. package.path' % CWD) sandbox = lua.eval("require('sandbox')") lua_script = open(os.path.join(CWD, '..', 'test.lua')).read() result = sandbox.run('function main(request) ' + lua_script + ' end') if result is True: body = sandbox.env["main"](i_request) return HttpResponse(body) return HttpResponse('Failed')
def load_from_existing_overrides_str(content: str): content = "function()\n" + content + "\nend" lua = LuaRuntime(unpack_returned_tuples=True) modinfos_func = lua.eval(content) modinfos_lua = modinfos_func() modinfos = OrderedDict() for modinfo in modinfos_lua and modinfos_lua.items() or []: modinfos[modinfo[0]] = ModInfos._load_from_configs_entry( modinfo[1]) modinfos[modinfo[0]].set_workshop_id(modinfo[0]) return ModInfos(modinfos)
def __init__(self): self.keys = {} self.scripts = {} self.watches = set() self.execute_map = {} self.cursors = {} self.lua_proxy = self.get_lua_proxy() self.lua = LuaRuntime(encoding=None, unpack_returned_tuples=True) for _, func in inspect.getmembers(self, predicate=inspect.ismethod): if hasattr(func, 'redis_command'): self.execute_map[func.redis_command] = func
def execute(self): """Отложенная инициализация self.globals""" # потому что объект LuaRuntime нельзя передать между процессами # lua._state cannot be converted to a Python object for pickling # noinspection PyArgumentList lua = LuaRuntime(unpack_returned_tuples=False) self.globals = lua.globals() # хак, после которого внезапно начинает работать require() self.globals.package.path = os.path.join( DIR_PATTERNS, '?.lua') + ';' + self.globals.package.path lua.execute(self.lua_code)
def __init__(self, planet): lua = LuaRuntime() self.planet = planet self.planet_regions_file = pathlib.Path( "../../Core3/MMOCoreORB/bin/scripts/managers/spawn_manager/" + planet + "_regions.lua") package_path_setup = 'package.path = package.path .. ";../../Core3/MMOCoreORB/bin/?.lua"\n' return_statement = "\nreturn " + planet + "_regions" regions = lua.execute(package_path_setup + self.planet_regions_file.read_text() + return_statement) self.regions = [] for lua_region in regions.values(): region = Region(lua_region) self.regions.append(region)
def main(): lua = LuaRuntime(unpack_returned_tuples=True) lua_main = lua.eval("require 'lua_main'") lua_main.init("test.txt") analysis = lua_main.get_analysis() transaction_table = lua_main.get_trans_table() root = Tk() text = TextFrame(root, analysis) graphs = DrawFrame(root, transaction_table) root.geometry("400x100+300+300") root.mainloop()
def __init__(self, username, accountname, apikey): self.username = username self.accountName = accountname self.apiKey = apikey self.lua = LuaRuntime() self.urlParser = re.compile('([a-zA-Z0-9_-]+)/(\d+)') self.waList = {} self.waIgnored = {} self.uidCache = {} self.idCache = {} self.dataCache = {'slugs': [], 'uids': [], 'ids': []} if self.username == 'DISABLED': self.username = '' if not os.path.isfile(Path(f'WTF/Account/{self.accountName}/SavedVariables/WeakAuras.lua')): raise RuntimeError('Incorrect WoW account name!')
def __init__(self, server, chatbot): # Init interpreter, create functions/namespaces in Lua's global state self.lua = LuaRuntime(unpack_returned_tuples=True) self.lua.execute(load_script("lua_bridge/init.lua")) # Params: str:namespace, str:name, pyfunc:func self.new_bind = self.lua.eval("bridge.new_bind") # Params: str:namespace self.new_namespace = self.lua.eval("bridge.new_namespace") self.lua.eval("log.info(\"Initialisation complete\")") self.server = server self.chatbot = chatbot self.create_binds()
def is_constraint_satisfied(self, vars: List[Self], vals: List[Optional[float]]) -> bool: if self.constraint is None: return True lua = LuaRuntime() for var, val in zip(vars, vals): if val is None: continue if isinstance(var.range, CategoricalRange): val = var.range.choices[int(val)] # type: ignore lua.execute("{} = {}".format(var.name, repr(val))) return lua.eval(self.constraint)
def parse_storage(self): self.lua = LuaRuntime() self.urlParser = re.compile('(\w+)/(\d+)') with open(Path(f'WTF/Account/{self.accountName}/SavedVariables/WeakAuras.lua'), 'r', encoding='utf-8') as file: data = file.read().replace('WeakAurasSaved = {', '{') wadata = self.lua.eval(data) for wa in wadata['displays']: if wadata['displays'][wa]['url']: search = self.urlParser.search(wadata['displays'][wa]['url']) if search.group(1) and search.group(2): self.uidCache[wadata['displays'][wa]['uid']] = search.group(1) self.idCache[wadata['displays'][wa]['id']] = search.group(1) if not wadata['displays'][wa]['parent'] and not wadata['displays'][wa]['ignoreWagoUpdate']: if wadata['displays'][wa]['skipWagoUpdate']: self.waIgnored[search.group(1)] = int(wadata['displays'][wa]['skipWagoUpdate']) self.waList[search.group(1)] = int(search.group(2))
def xm_machine_init(): impl = {"lua": LuaRuntime(unpack_returned_tuples=True)} lgl = impl["lua"].globals() xmbuiltins.register(impl["lua"]) xmos.register(impl["lua"]) xmpath.register(impl["lua"]) xmprocess.register(impl["lua"]) xmsandbox.register(impl["lua"]) if platform in ("win32", "cygwin"): lgl._HOST = "windows" elif platform == "darwin": lgl._HOST = "macosx" elif platform == "linux": lgl._HOST = "linux" elif os.name == "posix": lgl._HOST = "unix" else: lgl._HOST = "unknown" # XXX: deal other arch lgl._ARCH = "i386" if architecture()[0] == "32bit" else "x86_64" lgl._NULDEV = os.devnull version = xm_version() lgl._VERSION = "%d.%d.%d.%d" % (version["major"], version["minor"], version["alter"], version["build"]) lgl._VERSION_SHORT = "%d.%d.%d" % (version["major"], version["minor"], version["alter"]) impl["lua"].execute("xmake={}") return impl
def startup(self): self.log.info('starting up emulator') self.channels = [None] self.dump = Queue() self.events = set() self.party = None self.queue = deque() self.scripts = {} self.tick = 0 self.lua = LuaRuntime() self.globals = self.lua.globals() for name in ExposedFunctions: self.globals[name] = getattr(self, name) self.lua.execute(emulation_package) for addon in self.addons: load_on_demand = addon['tags'].get('LoadOnDemand') if not load_on_demand: self._load_addon(addon) handler = self.scripts.get('OnLoad') if handler: handler(None) self.call_onevent('PLAYER_LOGIN', []) self.call_onevent('PLAYER_ENTERING_WORLD', []) self.status = 'active' self.runtime.activate(self) self.log.info('emulator startup complete')
def __init__(self, lua_file, *args, **kwargs): super(LuaWrapperPlugin, self).__init__(*args, **kwargs) self.runtime = LuaRuntime(unpack_returned_tuples=True) self.setup_globals() base_plugin = self.create_base_plugin() with open(lua_file, "r") as fh: data = fh.read() # Pass base plugin as arg to module self.lua_plugin = self.runtime.execute(data, base_plugin) # If the module doesn't return anything, use the base plugin reference # and assume it modified it anyway. if self.lua_plugin is None: self.lua_plugin = base_plugin
class MiniMaxLua: def __init__(self, umka): self.umka = umka self.lua = LuaRuntime(unpack_returned_tuples=True) def run(self, board, depth): self.nodes = 0 self.st = time.time() best_val = float('-inf') beta = float('inf') best_move = None minimax = self.lua.eval(""" local function minimax(board, depth, maximize, bestScore) if board.is_game_over() or depth <= 0 then return tree:heuristic(node) end local children = tree:children(node) if maximize then bestScore = -math.huge for i, child in ipairs(children) do bestScore = math.max(bestScore, minimax(tree, child, depth - 1, false)) end return bestScore else bestScore = math.huge for i, child in ipairs(children) do bestScore = math.min(bestScore, minimax(tree, child, depth - 1, true)) end return bestScore end end""") return minimax(self.umka.evaluate, board)
def test_lupa(): import lupa from lupa import LuaRuntime lua = LuaRuntime(unpack_returned_tuples=True) print lua.eval('1+1') lua_func = lua.eval('function(f, n) return f(n) end') def py_add1(n): return n+1 print lua_func(py_add1, 2) print lua.eval('python.eval(" 2 ** 2 ")') == 4 print lua.eval('python.builtins.str(4)') == '4'
def main(): context = { 'lexer': LuaLexer, } lua = LuaRuntime(unpack_returned_tuples=True) linteract(context, lua.execute, print_return=False)
async def evalraw(self, ctx: Context, *, code: str): """ Evaluates a lua command in the raw form. This does not go through the sandbox, and is owner only. """ lua = LuaRuntime(unpack_returned_tuples=True) if code.startswith("```"): code = code[3:] if code.endswith("```"): code = code[:-3] result = lua.execute(code) await ctx.send("```{}```".format(result))
def __init__(self): self.lua = LuaRuntime() self.urlParser = re.compile('/([a-zA-Z0-9_-]+)/(\d+)') self.list = {} self.ignored = {} self.uids = {} self.ids = {} self.data = {'slugs': [], 'uids': [], 'ids': []}
def __init__(self, factorio_path, locale: FactorioLocale): super(FactorioState, self).__init__() self.factorio_path = factorio_path self.locale = locale self.lua = LuaRuntime(unpack_returned_tuples=True) self.lua.execute(""" local old_require = require function require (module) local ok, m = pcall (old_require, module) -- if ok then return m -- end -- try getting module from internal strings end """) self.modlist = FactorioModList() self._load_libs(self.lua) self.modlist.add_mod('%s/data/base/' % self.factorio_path)
class ExecJS: def __init__(self, source, name, parent): """Throws LuaExceptions (LuaError or LuaSyntaxError)""" self.name = name self.source = source self.vapor_client = VaporClient() self.get_led_data = self.vapor_client.get_led_data self.runtime = LuaRuntime() self.render_function = None self.render_function = self.runtime.eval(source) if self.render_function is None: print "no render callback!" def getName(self): return self.name def render(self): try: self.render_function(self.vapor_client, time.time(), 35) # TODO get num leds self.vapor_client.strobe() except ReferenceError: print "There is an error in your javascript" self.parent.remove_me(self)
class LuaLoader(object): def __init__(self, root_folder): self.lua = LuaRuntime(unpack_returned_tuples=True) self.function_cache = {} self.root_folder = root_folder def load_func(self, name): """ Loads a function from disk and gives it an ID. """ uid = str(uuid.uuid4()) path = os.path.join(self.root_folder, name) self.function_cache[uid] = self.lua.eval(open(path).read()) return uid def get_func(self, id): """ Returns the function based on the random id """ return self.function_cache[id]
def __init__(self): self.lua = LuaRuntime() self.lua.execute(_LUA_HELPERS)
import lupa from lupa import LuaRuntime lua = LuaRuntime() func = lua.eval('require("linerecog.lua")') def get_points(): return_data = func() result = [] # In volgorde left,top, right, bottom for row in return_data.values(): t = [] for point in row.values(): t.append((point[1],point[2])) result.append(t) return result
class LuaWrapperPlugin(PluginObject): def __init__(self, lua_file, *args, **kwargs): super(LuaWrapperPlugin, self).__init__(*args, **kwargs) self.runtime = LuaRuntime(unpack_returned_tuples=True) self.setup_globals() base_plugin = self.create_base_plugin() with open(lua_file, "r") as fh: data = fh.read() # Pass base plugin as arg to module self.lua_plugin = self.runtime.execute(data, base_plugin) # If the module doesn't return anything, use the base plugin reference # and assume it modified it anyway. if self.lua_plugin is None: self.lua_plugin = base_plugin def setup_globals(self): lua_globals = self.runtime.globals() lua_globals["import"] = self.import_python lua_globals["print"] = self.print_function def create_base_plugin(self): """ Create a base plugin Lua table that other plugins may "sub-class" :return: """ # table() and table_from() break the debugger somehow (breakpoints # stop working - pydevd.settrace() sometimes fixes it) so just make the # table in Lua from the start. table = self.runtime.execute("return {}") # Reference to self table["python_plugin"] = self # Basic plugin attributes table["info"] = self.info table["module"] = self.module table["logger"] = self.logger table["commands"] = self.commands table["events"] = self.events table["factory_manager"] = self.factory_manager table["plugins"] = self.plugins table["storage"] = self.storage # Helper methods table["import"] = self.import_python return table def __getattr__(self, item): return getattr(self.lua_plugin, item) def import_python(self, module, package=None): return importlib.import_module(module, package) def print_function(self, *args): self.logger.info("\t".join(str(arg) for arg in args)) def _run_from_lua_plugin(self, func_name, *args): """ Helper method to call functions from the Lua plugin, if they exist. :param func_name: :param args: Args to pass to Lua function :return: """ func = getattr(self.lua_plugin, func_name) if callable(func): return func(*args) return None def deactivate(self): return self._run_from_lua_plugin("deactivate") def setup(self): return self._run_from_lua_plugin("setup") def reload(self): return self._run_from_lua_plugin("reload")
class FactorioState(object): LUA_LIBS = ['util', 'dataloader', 'autoplace_utils', 'story', 'defines'] def __init__(self, factorio_path, locale: FactorioLocale): super(FactorioState, self).__init__() self.factorio_path = factorio_path self.locale = locale self.lua = LuaRuntime(unpack_returned_tuples=True) self.lua.execute(""" local old_require = require function require (module) local ok, m = pcall (old_require, module) -- if ok then return m -- end -- try getting module from internal strings end """) self.modlist = FactorioModList() self._load_libs(self.lua) self.modlist.add_mod('%s/data/base/' % self.factorio_path) @staticmethod def table_to_dict(tab): tab_type = type(tab) ret = {} for k, v in tab.items(): if type(v) is tab_type: ret[k] = FactorioState.table_to_dict(v) else: ret[k] = v return ret def _load_libs(self, lua): lib_dir = '%s/data/core/lualib/' % self.factorio_path for lib in FactorioState.LUA_LIBS: FactorioState.require(lua, lib_dir, lib) FactorioState.require(lua, '%s/data/core' % self.factorio_path, 'data') @staticmethod def require(lua, path, module): os.chdir(path) if not lua.require(module): raise RuntimeError('Require failed: %s in %s' % (module, path)) def get_data(self): return FactorioState.table_to_dict(self.lua.globals()['data']['raw']) def load_mods(self): # load locale for mod in self.modlist.mod_order: locale_dir = '%s/locale/en/' % mod.path if os.path.exists(locale_dir): for fn in os.listdir(locale_dir): fn = os.path.join(locale_dir, fn) if os.path.isfile(fn) and fn.endswith('.cfg'): self.locale.load(fn) for mod in self.modlist.mod_order: print('Load %s' % mod.title) if os.path.exists(os.path.join(mod.path, 'data.lua')): self.load_mod(mod.path, 'data') for mod in self.modlist.mod_order: print('Load %s' % mod.title) if os.path.exists(os.path.join(mod.path, 'data-updates.lua')): self.load_mod(mod.path, 'data-updates') for mod in self.modlist.mod_order: print('Load %s' % mod.title) if os.path.exists(os.path.join(mod.path, 'data-final-fixes.lua')): self.load_mod(mod.path, 'data-final-fixes') def load_mod(self, path, name): important = [u'table', u'io', u'math', u'debug', u'package', u'_G', u'python', u'string', u'os', u'coroutine', u'bit32', u'util', u'autoplace_utils'] for p in list(self.lua.globals()['package']['loaded']): if p not in important: del self.lua.globals()['package']['loaded'][p] self.require(self.lua, path, name) def save_gfx(self, path, data=None): if data is None: print('got data') data = self.get_data() for k, v in data.items(): if type(v) is dict: self.save_gfx(path, v) pass elif k == 'icon': icon_path = data['icon'].split('/') if icon_path[0] not in self.modlist.path_map: print('Unknown content path %s for %s/%s' % (icon_path[0], data['type'], data['name'])) continue icon_path[0] = self.modlist.path_map[icon_path[0]] icon_path = '/'.join(icon_path) out_dir = '%s/%s' % (path, data['type']) out_path = '%s/%s.png' % (out_dir, data['name']) mkdir_p(out_dir) if os.path.exists(out_path): print('Overwriting %s/%s' % (data['type'], data['name'])) shutil.copy2(icon_path, out_path)
import lupa from lupa import LuaRuntime lua = LuaRuntime(unpack_returned_tuples=True) sandbox = lua.require("sandbox") robotFunctions = lua.eval( "{\ thingy = print,\ }" ) sandbox.add(robotFunctions) while True: print("Code to run?") luacode = input("> ") print(sandbox.run(luacode))
# Run functional tests using lua, busted and the python client import os import sys import textwrap from lupa import LuaRuntime, as_attrgetter from neovim import Nvim, spawn_session # Extract arguments busted_script = sys.argv[1] busted_argv = sys.argv[2:] # Setup a lua state for running busted lua = LuaRuntime(unpack_returned_tuples=True) lua_globals = lua.globals() # helper to transform iterables into lua tables list_to_table = lua.eval(''' function(l) local t = {} for i, item in python.enumerate(l) do t[i + 1] = item end return t end ''') dict_to_table = lua.eval(''' function(d) local t = {} for k, v in python.iterex(d.items()) do t[k] = v end
import lupa from lupa import LuaRuntime import socket import threading import sys import hashlib import hmac from Crypto.Cipher import AES import json import copy lua = LuaRuntime(unpack_returned_tuples=True, encoding=None) lua_fun_queue = [] MAINFILE = '../esp/main.lua' def get_file_contents(f): with open(f, 'r') as f: return f.read() class lua_file(object): files = { 'config.json': get_file_contents('../esp/config.json'), 'keys.json': get_file_contents('../keysets/testing.json'), } last_file = None @staticmethod def exists(filename): return filename in lua_file.files
class Emulator(object): def __init__(self, runtime, character, enabled_addons=None): self.addons = [] self.character = character self.guild = None self.log = logging.getLogger(character.name.lower()) self.name = character.name.lower() self.runtime = runtime self.shell = None self.status = 'inactive' for addon in runtime.addons: if not enabled_addons or addon['name'] in enabled_addons: self.addons.append(addon.copy()) runtime.emulators[self.name] = self def __repr__(self): return 'Emulator(%r, %r)' % (self.name, self.status) @property def active(self): return self.status == 'active' def call_onevent(self, event, args): self.log.info('%s: %r', event, args) if self.shell: self.shell.notify('%s: %r' % (event, args)) handler = self.scripts.get('OnEvent') if handler and event in self.events: return handler(event, *args) def call_onupdate(self): handler = self.scripts.get('OnUpdate') if handler: tick = time.time() if self.tick: handler(None, tick - self.tick) else: handler(None, 0.0) self.tick = tick def queue_event(self, event, args): self.queue.append((event, args)) def restart(self): if self.active: self.shutdown() self.startup() def run(self): queue = self.queue while queue: self.call_onevent(*queue.popleft()) self.call_onupdate() def shutdown(self): self.log.info('shutting down emulator') self.call_onevent('PLAYER_LOGOUT', []) self.status = 'inactive' self.runtime.deactivate(self) self.log.info('emulator shutdown complete') def startup(self): self.log.info('starting up emulator') self.channels = [None] self.dump = Queue() self.events = set() self.party = None self.queue = deque() self.scripts = {} self.tick = 0 self.lua = LuaRuntime() self.globals = self.lua.globals() for name in ExposedFunctions: self.globals[name] = getattr(self, name) self.lua.execute(emulation_package) for addon in self.addons: load_on_demand = addon['tags'].get('LoadOnDemand') if not load_on_demand: self._load_addon(addon) handler = self.scripts.get('OnLoad') if handler: handler(None) self.call_onevent('PLAYER_LOGIN', []) self.call_onevent('PLAYER_ENTERING_WORLD', []) self.status = 'active' self.runtime.activate(self) self.log.info('emulator startup complete') def _get_addon(self, id): if isinstance(id, dict): return id elif isinstance(id, basestring): for addon in self.addons: if addon['name'] == id: return addon try: return self.addons[id - 1] except IndexError: return @exposed def GetAddOnMetadata(self, id, field): addon = self._get_addon(id) if addon: return addon['tags'].get(field) @exposed def GetNumAddOns(self): return len(self.addons) @exposed def GetNumPartyMembers(self): party = self.party if party and party.type == 'party': return len(party) else: return 0 @exposed def GetNumRaidMembers(self): raid = self.party if raid and raid.type == 'raid': return len(raid) else: return 0 @exposed def GetRealmName(self): return self.runtime.realm @exposed def GetTime(self): return time.time() @exposed def IsAddOnLoaded(self, id): addon = self._get_addon(id) return (addon and addon.get('loaded')) @exposed def IsInGuild(self): return bool(self.guild) @exposed def JoinPermanentChannel(self, name, password=None, frameId=None, enable_voice=False): channel = self.runtime.get_channel(name) @exposed def LeaveChannelByName(self, name): pass @exposed def RegisterAddonMessagePrefix(self, prefix): return True @exposed def SendAddonMessage(self, prefix, text, type, target=None): self.runtime.send_addon_message(self, prefix, text, type, target) @exposed def _dump(self, *args): self.dump.put(args) @exposed def _dump_to_shell(self, content): if self.shell: self.shell.notify(content) @exposed def _get_addon_info(self, id): addon = self._get_addon(id) if addon: return [addon['name'], addon['tags'].get('Title'), addon['tags'].get('Notes'), True, (addon['tags'].get('LoadOnDemand') or addon.get('loaded'))] @exposed def _get_character(self, field=None): return (getattr(self.character, field) if field else self.character) @exposed def _get_channel_name(self, id): try: id = int(id) except ValueError: for i, channel in enumerate(self.channels[1:]): if channel.name.lower() == id.lower(): return [i, channel.name] else: return [0, None] else: if id in self.channels: return [id, self.channels[id].name] else: return [0, None] @exposed def _get_current_date(self): return datetime.now() @exposed def _is_event_registered(self, event): self.log.debug('_is_event_registered(%r)', event) return event in self.events @exposed def _load_addon(self, id): addon = self._get_addon(id) if not addon: return if addon.get('loaded'): return True default_path = self.globals.package.path self.globals.package.path = '%s/?.lua;%s' % (addon['path'], default_path) self.log.info("attempting to load addon '%s'", addon['name']) for filename in addon['files']: if filename.endswith('.lua'): self.log.info("attempting to inject lua file '%s/%s'", addon['name'], filename) self.lua.require(filename[:-4]) # load saved variables here self.call_onevent('ADDON_LOADED', [addon['name']]) self.globals.package.path = default_path addon['loaded'] = True @exposed def _send_addon_message(self, prefix, content, channel): pass @exposed def _set_script(self, script, func): self.log.debug('_set_script(%r, %r)', script, func) if func: self.scripts[script] = func elif script in self.scripts: del self.scripts[script] @exposed def _toggle_event(self, event, receiving): if receiving: self.events.add(event) else: self.events.discard(event)
class LuaModule(object): def __init__(self): self.lua = LuaRuntime(register_eval=False, attribute_filter=self.filter) # A subset of the standard library self.env = self.lua.eval("""{ assert=assert, error=error, ipairs=ipairs, next=next, pairs=pairs, pcall=pcall, select=select, tonumber=tonumber, tostring=tostring, type=type, unpack=unpack, _VERSION=_VERSION, xpcall=xpcall, coroutine=coroutine, string=string, table=table, math=math, os={ clock=os.clock, date=os.date, difftime=os.difftime, time=os.time } }""") self.env.kb = self.lua.table() self.lua.globals()['kb_private'] = self.lua.table( webget=self.lua_webget, schedule_at=self.lua_schedule_at, schedule_cron=self.lua_schedule_cron ) self.env.kb['webget'] = self.lua.eval('function(url, callback) kb_private.webget(url, callback) end') self.env.kb['schedule_at'] = self.lua.eval('function(when, user_data, callback) kb_private.schedule_at(when, user_data, callback) end') self.env.kb['schedule_cron'] = self.lua.eval('function (period, user_data, callback) kb_private.schedule_cron(period, user_data, callback) end') self.events = self.lua.table() self.env.events = self.events self.lua.globals().env = self.env self.run = self.lua.eval(""" function (untrusted_code) if untrusted_code:byte(1) == 27 then return nil, "binary bytecode prohibited" end local untrusted_function, message = loadstring(untrusted_code) if not untrusted_function then return nil, message end setfenv(untrusted_function, env) return pcall(untrusted_function) end """) self.lua.execute(""" counter = 0 running = 1 debug.sethook(function (event, line) counter = counter + 1 if not running or counter > 10000 then error("That's enough!") end end, "", 1) """) def filter(self, o, attribute, is_setting): raise AttributeError("forbidden: %s.%s" % (o, attribute)) def irc_wrapper(self, irc): wrapper = self.lua.table() wrapper['_network'] = irc wrapper['_send_message'] = lambda channel, message: m('irc_helpers').message(irc, channel, message) wrapper.send_message = self.lua.eval("function (self, channel, message) self._send_message(channel, message) end") return wrapper def channel_wrapper(self, irc, channel): wrapper = self.lua.table() wrapper['irc'] = self.irc_wrapper(irc) wrapper['_send'] = lambda message: m('irc_helpers').message(irc, channel, message) wrapper['send'] = self.lua.eval("function (self, message) self._send(message) end") try: chan = m('chantrack').network(irc)[channel] except KeyError: wrapper['members'] = self.lua.table() else: wrapper['members'] = self.list_to_table([self.user_wrapper(x) for x in chan.users.values()]) wrapper['topic'] = chan.topic wrapper['name'] = channel return wrapper def user_wrapper(self, user): if user is None: return None wrapper = self.lua.table( hostname=user.hostname, nick=user.nick, ident=user.ident, realname=getattr(user, 'realname', None), modes=getattr(user, 'modes', None), _send=lambda message: m('irc_helpers').message(irc, user.nick, message), send=self.lua.eval('function(self, message) self._send(message) end') ) return wrapper def event_message(self, irc, channel, origin, command, args): if self.events.received_command: self.lua.globals().counter = 0 self.events.received_command(self.channel_wrapper(irc, channel), self.user_wrapper(origin), command, self.list_to_table(args)) def list_to_table(self, iter): return self.lua.table(*iter) def lua_webget(self, url, callback): def do_callback(): try: f = urllib2.urlopen(url) result = f.read() except urllib2.URLError as e: callback(False, str(e)) else: callback(True, result) threading.Thread(target=do_callback).start() def lua_schedule_at(self, when, user_data, callback): try: m('cron').add_at(when, callback, when, user_data) except ModuleNotLoaded: return False else: return True def lua_schedule_cron(self, period, user_data, callback): try: m('cron').add_cron(period, callback, user_data) except ModuleNotLoaded: return False else: return True def stop(self): self.lua.globals().running = 0
from lupa import LuaRuntime lua = LuaRuntime() lua.require("app/battle/src/test_main") #reload_func = lua.eval('''function() reload_lua_config(); end''') #reload_func() #print("lua runtime")
# coding:utf8 from lupa import LuaRuntime lua = LuaRuntime() lua.require("src/test_main") #TYPE_GUIDE = 0 --演示关卡 #TYPE_STAGE_NORMAL = 1 -- 普通关卡(剧情), stage_config #TYPE_STAGE_ELITE = 2 -- 精英关卡, special_stage_config #TYPE_STAGE_ACTIVITY = 3 -- 活动关卡, special_stage_config #TYPE_TRAVEL = 4 --travel #TYPE_PVP = 6 --pvp #TYPE_WORLD_BOSS = 7 --世界boss #TYPE_MINE_MONSTER = 8 -- 攻占也怪 #TYPE_MINE_OTHERUSER = 9 -- 攻占其他玩家 #func = lua.eval('''function() return start(); end''') #print(func()) func = lua.eval('''function(fightData, fightType) setData(fightData, fightType); return start(); end''') def construct_battle_unit(unit): # 构造战斗单元 return lua.table( no = unit.no, quality = unit.quality, hp = unit.hp,
import magma as m m.set_mantle_target("ice40") import mantle as mantle import lupa from lupa import LuaRuntime lua = LuaRuntime(unpack_returned_tuples=True) lua.execute("package.path='./?.lua;/home/jhegarty/rigel/?.lua;/home/jhegarty/rigel/src/?.lua;/home/jhegarty/rigel/modules/?.lua;/home/jhegarty/rigel/misc/?.lua;/home/jhegarty/rigel/misc/compare/?.lua;/home/jhegarty/rigel/examples/?.lua'") ############################################## # generate a rigel module like in regular lua... R = lua.require("rigel") G = lua.require("generators") RM = lua.require("modules") types = lua.require("types") C = lua.require("examplescommon") inp = R.input( types.uint(8) ) a = R.apply("a", C.plus100(types.uint(8)), inp) b = R.apply("b", C.plus100(types.uint(8)), a) p200 = RM["lambda"]( "p200", inp, b ) ####################################### def rigelTypeToMagmaType(ty): assert(types.isType(ty)) if ty.isUint(ty): return m.UInt(ty.verilogBits(ty)) else: assert(false)
import lupa from lupa import LuaRuntime lua = LuaRuntime(unpack_returned_tuples=True) fileName = "test_json/3.json" repo_name = "aaa" meta_version = "bbbb" comd = "" comd += "fileName = " + "'" + fileName + "'\n" comd += "repo_name = " + "'" + repo_name + "'\n" comd += "meta_version = " + "'" + meta_version + "'\n" print comd # lua.eval("dostring("+comd+")") fo = open("jsonForPY.lua", "w+") fo.write(comd) fo.close() lua.eval("dofile('jsonForPY.lua')") a = lua.eval("dofile('jsonCompletion.lua')") print a['appname'] print a['procs']['bar']['port']['port']
def _read_esprc(path): ''' Read the .esprc file using Lua Parameters ---------- path : string Path to the .esprc file Returns ------- (esphost, espport, espprotocol) ''' esphost = None espport = None espprotocol = None if not os.path.isfile(path): return esphost, espport, espprotocol try: from lupa import LuaRuntime lua = LuaRuntime() lua.eval('dofile("%s")' % path) lg = lua.globals() except ImportError: import subprocess import tempfile lua_script = tempfile.TemporaryFile(mode='w') lua_script.write(''' if arg[1] then dofile(arg[1]) for name, value in pairs(_G) do if name:match('esp') then print(name .. ' ' .. tostring(value)) end end end ''') lua_script.seek(0) class LuaGlobals(object): pass lg = LuaGlobals() config = None try: config = subprocess.check_output('lua - %s' % path, stdin=lua_script, shell=True).strip().decode('utf-8') except (OSError, IOError, subprocess.CalledProcessError): pass finally: lua_script.close() if config: for name, value in re.findall(r'^\s*(esp\w+)\s+(.+?)\s*$', config, re.M): setattr(lg, name, value) else: # Try to parse manually config = re.sub(r'\-\-.*?$', r' ', open(path, 'r').read(), flags=re.M) for name, value in re.findall(r'\b(esp\w+)\s*=\s*(\S+)(?:\s+|\s*$)', config): setattr(lg, name, eval(value)) try: esphost = str(lg.esphost) except: sys.sterr.write('ERROR: Could not access esphost setting\n') sys.exit(1) try: espport = int(lg.espport) except: sys.sterr.write('ERROR: Could not access espport setting\n') sys.exit(1) try: if lg.espprotocol: espprotocol = str(lg.espprotocol) except: pass return esphost, espport, espprotocol
def __init__(self): self.lua = LuaRuntime(register_eval=False, attribute_filter=self.filter) # A subset of the standard library self.env = self.lua.eval("""{ assert=assert, error=error, ipairs=ipairs, next=next, pairs=pairs, pcall=pcall, select=select, tonumber=tonumber, tostring=tostring, type=type, unpack=unpack, _VERSION=_VERSION, xpcall=xpcall, coroutine=coroutine, string=string, table=table, math=math, os={ clock=os.clock, date=os.date, difftime=os.difftime, time=os.time } }""") self.env.kb = self.lua.table() self.lua.globals()['kb_private'] = self.lua.table( webget=self.lua_webget, schedule_at=self.lua_schedule_at, schedule_cron=self.lua_schedule_cron ) self.env.kb['webget'] = self.lua.eval('function(url, callback) kb_private.webget(url, callback) end') self.env.kb['schedule_at'] = self.lua.eval('function(when, user_data, callback) kb_private.schedule_at(when, user_data, callback) end') self.env.kb['schedule_cron'] = self.lua.eval('function (period, user_data, callback) kb_private.schedule_cron(period, user_data, callback) end') self.events = self.lua.table() self.env.events = self.events self.lua.globals().env = self.env self.run = self.lua.eval(""" function (untrusted_code) if untrusted_code:byte(1) == 27 then return nil, "binary bytecode prohibited" end local untrusted_function, message = loadstring(untrusted_code) if not untrusted_function then return nil, message end setfenv(untrusted_function, env) return pcall(untrusted_function) end """) self.lua.execute(""" counter = 0 running = 1 debug.sethook(function (event, line) counter = counter + 1 if not running or counter > 10000 then error("That's enough!") end end, "", 1) """)
elif message[0] == 'RIGHTSTOP': id_ = message[1] if not has_lock(id_): return_message = 'NO_LOCK' else: if not TESTING_MODE: try: manualDrive.delete_command('right') manual = manualDrive.run() return_message = 'SUCCES' except: return_message = 'FAILURE' else: return_message = 'SUCCES' elif message[0] == 'COMMAND': id_= message[2] if not has_lock(id_): return_message = 'NO_LOCK' else: print parse_command(message[1]) if not TESTING_MODE: lua = LuaRuntime() func = lua.eval("require('linerecog')") func(commands,conroller.get_engine_distance,controller.start_commmand,controller.stop_commmand,controller.drive_distance) return_message = 'SUCCES' else: return_message = 'ILLEGAL_MESSAGE' print 'Return message: ', return_message socket.send(return_message)