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 initialize_lua(ctx): assert isinstance(ctx, ExpandCtx) assert ctx.lua is None # Load Lua sandbox code. lua_sandbox = open("lua/sandbox.lua").read() def filter_attribute_access(obj, attr_name, is_setting): print("FILTER:", 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) lua.execute(lua_sandbox) lua.eval("lua_set_loader")(lambda x: lua_loader(ctx, x), mw_text_decode, mw_text_encode, lambda x: get_page_info(ctx, x), lambda x: get_page_content(ctx, x), fetch_language_name, lambda x: fetch_language_names(ctx, x)) ctx.lua = lua
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 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 getModInfo(self, root, moddir, t): modinfo = {} olddir = os.getcwd() os.chdir(self.modrootdir) if not os.path.exists(os.path.join(root, "json.lua")): shutil.copyfile(os.path.join(CONFIG_DIR, "json.lua"), os.path.join(root, "json.lua")) if os.path.exists(os.path.join(root, moddir, "modinfo.lua")): lua = LuaRuntime(unpack_returned_tuples=True) lua.require(os.path.join(moddir, "modinfo")) if os.path.exists(os.path.join(root, moddir, "modinfo_chs.lua")): lua.require(os.path.join(moddir, "modinfo_chs")) modinfo["name"] = lua.eval('name').strip() modinfo["server_only_mod"] = lua.eval('server_only_mod') modinfo["all_clients_require_mod"] = lua.eval( 'all_clients_require_mod') modinfo["client_only_mod"] = lua.eval('client_only_mod') if t != "basic": modinfo["description"] = lua.eval('description').strip() modinfo["author"] = lua.eval('author').strip() modinfo["version"] = lua.eval('version').strip() lua.require("json") config_json_str = lua.eval( 'encode_compliant(configuration_options)') modinfo["configuration_options"] = json.loads(config_json_str) os.chdir(olddir) return modinfo
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 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)
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)
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 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
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)
class Lua(object): def __init__(self, setup): self.runtime = LuaRuntime() self.runtime.eval('function(pow) math.pow = pow end')(pow) setup(self.runtime) def evaluate(self, evaluatable): with self.add_searchpaths(evaluatable.get_lua_searches()): for m in evaluatable.get_lua_modules(): self.runtime.eval('require("%s")' % m) return self @contextlib.contextmanager def add_searchpaths(self, ps): p, ps = (ps[0], ps[1:]) if ps else (None, ps) if p: self.set_searchpath('%s/?.lua;%s' % (p, self.runtime.eval('package.path'))) if ps: with self.add_searchpaths(ps): yield else: yield def set_searchpath(self, p): return self.runtime.eval('function(p) package.path = p end')(p) def dump_global(self, v): return Dumper().dump(self.runtime.eval(v))
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 createMinHash(self): # We are working with a processor that has 28 cores. step = 28 for start in range(0, self.n_points, step): threads = [] if start > self.n_points: break for col_j in range(start, start + step): if col_j >= self.n_points: break lua = LuaRuntime(unpack_returned_tuples=True, encoding=None) pop_index = lua.eval(self.lua_sparse) zeroes_index = lua.eval(self.lua_dense) t = threading.Thread(target=self.worker, args=(col_j, self.signatures[col_j], pop_index, zeroes_index)) threads.append(t) for t in threads: t.start() for t in threads: t.join()
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 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 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 new_runtime(): rt = LuaRuntime() lua_root = os.path.join(os.path.dirname(__file__), 'lua') path = os.path.join(lua_root, '?.lua') rt.eval("function(path) package.path = package.path .. ';' .. path end")( path) #rt.require('utils.common') rt.require('win.Fight.verify_manager') require_configs(rt, lua_root) reg_proto = rt.eval('protobuf.register') reg_proto(open(os.path.join(lua_root, 'config/poem.pb'), 'rb').read()) reg_proto(open(os.path.join(lua_root, 'config/config.pb'), 'rb').read()) #zip_loader = get_zip_loader(rt, '/tmp/test.zip') #set_loader(rt, zip_loader) #rt.require('test.xxx') return rt
def iter_dataframes(path): path = Path(path) lua = LuaRuntime(unpack_returned_tuples=False) assert path.exists() init_lua_file = Path(Path(__file__).parent, 'functions.lua') lua.execute(init_lua_file.read_text()) with path.open('r') as f: line = True while line: line = f.readline() if len(line) < 5 and not line.strip(): continue lua.execute('pre_hook()') try: lua.execute(line) except Exception as e: if 'LuaSyntaxError' in type(e).__name__: # sometimes tsm write into the file at the same time we read it raise RetryLater() from e else: raise finally: lua.execute('post_hook()') data = lua.eval('_G.datastack') lua.execute('_G.datastack = nil') if not data: continue download_time = int(data.downloadTime) tag = data.tag realm = data.realm filename = f"tsm_{realm.lower().replace('-', '_').replace(' ', '_')}" print("processing %s" % realm) fields = tuple(data.fields.values()) assert fields data = (sub.values() for sub in data.data.values()) df = pd.DataFrame(data, columns=fields) if len(df) == 0: print("no data for %s" % filename) continue df['date'] = pd.to_datetime(download_time, unit='s') for col in ('marketValue', 'minBuyout', 'historical', 'numAuctions'): if col in df: df[col] = pd.to_numeric(df[col], downcast='integer') df['itemString'] = df['itemString'].astype(str) yield filename, df
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 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 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 load_recipes(factorio_dir: str): """ Load recipes from Factorio data directory by interpreting the Lua scripts. """ lua = LuaRuntime(unpack_returned_tuples=True) preamble = ''' aggregator = {} data = {} data["extend"] = function (data, list_of_things) for key, thing in ipairs(list_of_things) do table.insert(aggregator, thing) end end ''' lua.execute(preamble) recipe_files = [ 'data/base/prototypes/recipe.lua', ] for filename in recipe_files: full_path = path.join(factorio_dir, path.normpath(filename)) with open(full_path, 'r') as fp: lua.execute(fp.read()) def lua2py(obj): t = lua_type(obj) if t == 'table': keys = list(obj.keys()) is_sequence = keys == [i + 1 for i in range(len(keys))] if is_sequence: return [lua2py(v) for v in obj.values()] else: return {lua2py(k): lua2py(obj[k]) for k in keys} elif t is None: return obj else: raise ValueError(f'unsupported Lua type {t}') aggregator = lua.eval('aggregator') return lua2py(aggregator)
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)
def is_constraint_satisfied(self, vars: List[Self], vals: List[Optional[float]]) -> bool: if self.constraint is None: return True if not _lupa_available: raise RuntimeError( "Please install `lupa` to handle problems containing conditional search space." ) 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)
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]
class SandboxedLua: """A Lua runtime environment that's restricted to a sandbox. The sandbox is mostly implemented in Lua itself, and restricts the capabilities and data that code will be able to use. There are also some attempts to restrict resource usage, but I don't know how effective it is (and should probably be done on the OS level as well). """ 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 run_code(self, code: str) -> None: """Run Lua code inside the sandboxed environment.""" result = self.sandbox.run(code) if result is not True: raise LuaError(result[1]) def get_lua_function(self, name: str) -> Optional[Callable]: """Return the named Lua function so it can be called on Python data.""" return self.sandbox.env[name] def run_lua_function(self, name: str, *args: Any) -> None: """Run the named Lua function, passing in the remaining args.""" function = self.get_lua_function(name) if not function: raise ValueError(f"No Lua function named {name} exists") function(*args)
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)
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
def filter_attribute_access(obj, attr_name, is_setting): print("FILTER:", 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) lua.execute(lua_sandbox) lua.eval("lua_set_loader")(lua_loader, mw_text_decode, mw_text_encode, get_page_info, fetch_language_name, fetch_language_names) # Process test page page = open("tests/animal.txt").read() page_title = "animal" page = wikitext.preprocess_text(page) print("=== Expanding templates") page = expand_listed_templates(page_title, page, templates, invoke_fn) # XXX expand only need_pre_expand here (now expanding all for testing purposes) print(page) print("=== Parsing") tree = wikitext.parse("animal", page) print("=== Printing") wikitext.print_tree(tree)
class WagoUpdater: 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 parse_storage(self): 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 is not None and 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)) @retry('Failed to parse WeakAura data.') def check_updates(self): wa = [[], []] if len(self.waList) > 0: payload = requests.get(f'https://data.wago.io/api/check/weakauras?ids={",".join(self.waList.keys())}', headers={'api-key': self.apiKey, 'User-Agent': HEADERS['User-Agent']}).json() if 'error' in payload or 'msg' in payload: raise RuntimeError for aura in payload: if 'username' in aura and (not self.username or aura['username'] != self.username): if not aura['slug'] in self.waList: aura['slug'] = aura['_id'] if aura['version'] > self.waList[aura['slug']] and \ (not aura['slug'] in self.waIgnored or (aura['slug'] in self.waIgnored and aura['version'] != self.waIgnored[aura['slug']])): wa[0].append(aura['name']) self.update_aura(aura) else: wa[1].append(aura['name']) wa[0].sort() wa[1].sort() return wa @retry('Failed to parse WeakAura data.') def update_aura(self, aura): raw = requests.get(f'https://data.wago.io/api/raw/encoded?id={aura["slug"]}', headers={'api-key': self.apiKey, 'User-Agent': HEADERS['User-Agent']}).text slug = f' ["{aura["slug"]}"] = {{\n name = [=[{aura["name"]}]=],\n author = [=[' \ f'{aura["username"]}]=],\n encoded = [=[{raw}]=],\n wagoVersion = [=[' \ f'{aura["version"]}]=],\n wagoSemver = [=[{aura["versionString"]}]=],\n }},\n' uids = '' ids = '' for u in self.uidCache: if self.uidCache[u] == aura["slug"]: uids = uids + f' ["{u}"] = [=[{aura["slug"]}]=],\n' for i in self.idCache: if self.idCache[i] == aura["slug"]: ids = ids + f' ["{i}"] = [=[{aura["slug"]}]=],\n' self.dataCache['slugs'].append(slug) self.dataCache['uids'].append(uids) self.dataCache['ids'].append(ids) def install_data(self): with open(Path('Interface/AddOns/WeakAurasCompanion/data.lua'), 'w', newline='\n') as out: out.write('-- file generated automatically\nWeakAurasCompanion = {\n slugs = {\n') for slug in self.dataCache['slugs']: out.write(slug) out.write(' },\n uids = {\n') for uid in self.dataCache['uids']: out.write(uid) out.write(' },\n ids = {\n') for ids in self.dataCache['ids']: out.write(ids) out.write(' },\n stash = {\n }\n}') def install_companion(self, client_type, force): if not os.path.isdir(Path('Interface/AddOns/WeakAurasCompanion')) or force: Path('Interface/AddOns/WeakAurasCompanion').mkdir(exist_ok=True) with open(Path('Interface/AddOns/WeakAurasCompanion/WeakAurasCompanion.toc'), 'w', newline='\n') as out: out.write(f'## Interface: {"11304" if client_type == "wow_classic" else "80300"}\n## Title: WeakAu' f'ras Companion\n## Author: The WeakAuras Team\n## Version: 1.1.0\n## Notes: Keep your WeakAu' f'ras updated!\n## X-Category: Interface Enhancements\n## DefaultState: Enabled\n## LoadOnDem' f'and: 0\n## OptionalDeps: WeakAuras, Plater\n\ndata.lua\ninit.lua') with open(Path('Interface/AddOns/WeakAurasCompanion/init.lua'), 'w', newline='\n') as out: out.write('-- file generated automatically\nlocal buildTimeTarget = 20190123023201\nlocal waBuildTime =' ' tonumber(WeakAuras and WeakAuras.buildTime or 0)\nif waBuildTime and waBuildTime > buildTim' 'eTarget then\n local loadedFrame = CreateFrame("FRAME")\n loadedFrame:RegisterEvent("ADDON' '_LOADED")\n loadedFrame:SetScript("OnEvent", function(_, _, addonName)\n if addonName ==' ' "WeakAurasCompanion" then\n local count = WeakAuras.CountWagoUpdates()\n if count' ' and count > 0 then\n WeakAuras.prettyPrint(WeakAuras.L["There are %i updates to your' ' auras ready to be installed!"]:format(count))\n end\n if WeakAuras.ImportHistory ' 'then\n for id, data in pairs(WeakAurasSaved.displays) do\n if data.uid and n' 'ot WeakAurasSaved.history[data.uid] then\n local slug = WeakAurasCompanion.uids[d' 'ata.uid]\n if slug then\n local wagoData = WeakAurasCompanion.slugs[' 'slug]\n if wagoData and wagoData.encoded then\n WeakAuras.Import' 'History(wagoData.encoded)\n end\n end\n end\n end\n ' ' end\n local emptyStash = true\n for _ in pairs(WeakAurasCompanion.stash) do\n' ' emptyStash = false\n end\n if not emptyStash and WeakAuras.StashShow then' '\n C_Timer.After(5, function() WeakAuras.StashShow() end)\n end\n end\n end)' '\nend\n\nif Plater and Plater.CheckWagoUpdates then\n Plater.CheckWagoUpdates()\nend') with open(Path('Interface/AddOns/WeakAurasCompanion/data.lua'), 'w', newline='\n') as out: out.write('-- file generated automatically\nWeakAurasCompanion = {\n slugs = {\n },\n uids = {\n },' '\n ids = {\n },\n stash = {\n },\n Plater = {\n slugs = {\n },\n uids = {\n ' ' },\n ids = {\n },\n stash = {\n },\n },\n}')
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 _read_casrc(path): ''' Read the .casrc file using Lua Parameters ---------- path : string Path to the .casrc file Returns ------- (cashost, casport, casprotocol) ''' cashost = None casport = None casprotocol = None if not os.path.isfile(path): return cashost, casport, casprotocol 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('cas') 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*(cas\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(cas\w+)\s*=\s*(\S+)(?:\s+|\s*$)', config): setattr(lg, name, eval(value)) try: cashost = str(lg.cashost) except: sys.sterr.write('ERROR: Could not access cashost setting\n') sys.exit(1) try: casport = int(lg.casport) except: sys.sterr.write('ERROR: Could not access casport setting\n') sys.exit(1) try: if lg.casprotocol: casprotocol = str(lg.casprotocol) except: pass return cashost, casport, casprotocol
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 return t end ''') def to_table(obj): if type(obj) in [tuple, list]: return list_to_table(list(to_table(e) for e in obj))
def getModInfo(self, moddir, t="all"): modinfo = {} root = self.dst_mod_dir olddir = os.getcwd() os.chdir(root) if not os.path.exists(os.path.join(root, "json.lua")): public.ExecShell( "cp -f " + os.path.join(self.dstserver_data_dir, "json.lua") + os.path.join(root, "json.lua")) if os.path.exists(os.path.join(root, moddir, "modinfo.lua")): lua = LuaRuntime(unpack_returned_tuples=True) lua.require(os.path.join(moddir, "modinfo")) if os.path.exists(os.path.join(root, moddir, "modinfo_chs.lua")): lua.require(os.path.join(moddir, "modinfo_chs")) modinfo["name"] = lua.eval('name').strip() modinfo["moddir"] = moddir t1 = lua.eval('server_only_mod') t3 = lua.eval('all_clients_require_mod') t2 = lua.eval('client_only_mod') modinfo['load_type'] = "服务端" if t1: modinfo['load_type'] = "服务端" if t2: modinfo['load_type'] = "客户端" if t3: modinfo['load_type'] = "所有人" modinfo["author"] = lua.eval('author').strip() modinfo["version"] = lua.eval('version').strip() lua.require("json") config_json_str = lua.eval( 'encode_compliant(configuration_options)') modinfo["configuration_options"] = json.loads(config_json_str) if modinfo["configuration_options"]: modinfo['configable'] = True else: modinfo['configable'] = False if t == "basic": modinfo["configuration_options"] = [] else: modinfo["description"] = lua.eval('description').strip() modinfo["server_only_mod"] = lua.eval('server_only_mod') modinfo["all_clients_require_mod"] = lua.eval( 'all_clients_require_mod') modinfo["client_only_mod"] = lua.eval('client_only_mod') os.chdir(olddir) return modinfo
#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, atk = unit.atk, physical_def = unit.physical_def, magic_def = unit.magic_def, hit = unit.hit, dodge = unit.dodge, cri = unit.cri, cri_coeff = unit.cri_coeff,
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']
import os import lupa from lupa import LuaRuntime # get the path of the print_string.lua file code_directory = os.path.split( os.path.dirname(os.path.realpath('__file__')) )[0] # get the path of the project directory, based on this file's absolute path external_lua_file_path = os.path.join( code_directory, 'lua_scripts', 'print_string.lua' ) # get the path of the print_string.lua file, which lives in the lua_scripts/ folder lua = LuaRuntime(unpack_returned_tuples=True) # create function for opening files open_file = lua.eval('function (filename) f = loadfile(filename)() end') # open the 'print_string.lua file print('loading external lua file...') open_file(external_lua_file_path) # opening that file dumps all the functions from that # file into lua.globals g = lua.globals() # obtain the print_string function contained within print_string.lua # call print_string on 'squirt' >> equivalent to print('squirt') print_string = g.print_string print_string('this string was printed by print_string()') # obtain the print_and_return_string contained within print_string.lua
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
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)
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))
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']