Beispiel #1
0
def sum_all_to_range_with_lua_python(end_range_number):
    start_time = time.time()

    lua_code = """
    function(n)
       sum = 0
       for i=1,n,1 do
           sum = sum + i
       end
       return sum
    end
    """
    lua_func = LuaRuntime(encoding=None).eval(lua_code)
    the_sum = lua_func(end_range_number)
    stop_time = time.time()
    return (end_range_number, stop_time - start_time, the_sum)
Beispiel #2
0
    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)
Beispiel #3
0
    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
Beispiel #4
0
 def parse_storage(self):
     self.lua = LuaRuntime()
     self.urlParser = re.compile('([a-zA-Z0-9_-]+)/(\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 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))
Beispiel #5
0
    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))
Beispiel #6
0
 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!')
Beispiel #7
0
    def __init__(self, path: Path, prototypes: Prototypes):
        self.path = path
        self.lua = LuaRuntime()
        self.prototypes = prototypes

        self.lua.execute(
            f"package.path = package.path .. ';{self.path.parent.as_posix()}/?.lua'"
        )
        self.lua.execute('''data = {
      extend = function(self, otherdata)
        if type(otherdata) ~= 'table' or #otherdata == 0 then
          error('Invalid prototype array in ' .. python.eval('prototype'))
        end
        for key, block in pairs(otherdata) do
          table.insert(self, block)
        end
      end
    }''')
Beispiel #8
0
    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)

        old = os.path.abspath(os.curdir)
        os.chdir('factorio-lua-tools')

        lua = LuaRuntime(unpack_returned_tuples=True)
        loader = lua.require('loader')

        # TODO this is awful
        lua.execute('defines = {}')
        lua.execute('defines.difficulty_settings = {}')
        lua.execute('defines.difficulty_settings.recipe_difficulty = {}')
        lua.execute('defines.difficulty_settings.recipe_difficulty.normal = 1')
        lua.execute(
            'defines.difficulty_settings.recipe_difficulty.expensive = 2')
        lua.execute('defines.difficulty_settings.technology_difficulty = {}')
        lua.execute(
            'defines.difficulty_settings.technology_difficulty.normal = 1')
        lua.execute(
            'defines.difficulty_settings.technology_difficulty.expensive = 2')
        lua.execute('defines.direction = {}')
        lua.execute('defines.direction.north = 0')
        lua.execute('defines.direction.east = 1')
        lua.execute('defines.direction.south = 2')
        lua.execute('defines.direction.west = 3')
        lua.execute('function log(x) end')

        core_path = '%s/data/core/' % self.factorio_path
        mod_paths = [mod.path for mod in self.modlist.mod_order]

        loader.load_data(lua.table_from([core_path] + mod_paths))

        os.chdir(old)

        self.data = FactorioState.table_to_dict(loader.data)
Beispiel #9
0
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)
Beispiel #10
0
def _get_dict_from_lua_source(code):
    def recursice_dict(lua_dict):
        d = {}
        is_list = True
        for key, value in lua_dict.items():
            if not isinstance(key, int):
                is_list = False

            if lupa.lua_type(value) == "table":
                value = recursice_dict(value)
            d[key] = value

        if is_list:
            return list(d.values())
        else:
            return d

    lua = LuaRuntime(unpack_returned_tuples=True)
    l_table = lua.execute(code)
    return recursice_dict(l_table)
Beispiel #11
0
def read_lua_table(file_name: Path) -> Optional[List]:
    """Read a single lua stat file, returning a dict."""
    fp_ = get_filehandle_maybe_gzip(file_name)
    file_contents = " ".join([f.decode('UTF-8') for f in fp_.readlines()])
    fp_.close()
    if file_contents == "placeholder":
        return None

    lua_code = f"\n function() \r\n local {file_contents} return misStats end"

    thread_count = 1
    lua_funcs = [
        LuaRuntime(encoding=None).eval(lua_code) for _ in range(thread_count)
    ]

    results: List[Dict] = [{}]

    def read_tab_func(i, lua_func):
        results[i] = lua_func()

    threads = [
        threading.Thread(target=read_tab_func, args=(i, lua_func))
        for i, lua_func in enumerate(lua_funcs)
    ]
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join()

    result = lua_tbl_to_py(results[0])
    results_out = []
    for res in result.values():
        tmp = result_to_flat_dict(res)
        entry = {
            'file_name': str(file_name),
            'pilot': tmp.pop('pilot'),
            'pilot_id': tmp.pop('id'),
            'record': tmp
        }
        results_out.append(entry)
    return results_out
Beispiel #12
0
    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)
Beispiel #13
0
def initialize_lua(ctx):
    assert ctx.lua is None
    # Load Lua sandbox code.
    lua_sandbox = open(lua_dir + "sandbox.lua").read()

    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)
    lua.execute(lua_sandbox)
    lua.eval("lua_set_loader")(
        lambda x: lua_loader(ctx, x), mw_text_decode, mw_text_encode,
        mw_text_jsonencode, lambda x, *rest: mw_text_jsondecode(ctx, x, *rest),
        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
Beispiel #14
0
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
Beispiel #15
0
 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()
Beispiel #16
0
class QKernel(Kernel):
    implementation = 'Q'
    implementation_version = '1.0'
    language = 'no-op'
    language_version = '0.1'
    language_info = {
        'name': 'Any text',
        'mimetype': 'text/plain',
        'file_extension': '.txt',
    }
    banner = "Q kernel - enjoy analytics"

    lua = LuaRuntime(unpack_returned_tuples=True)
    lua.execute("Q = require 'Q'")

    def do_execute(self,
                   code,
                   silent,
                   store_history=True,
                   user_expressions=None,
                   allow_stdin=False):
        if not silent:
            try:
                result = QKernel.lua.execute(code)
            except Exception as exc:
                result = str(exc)
            #with open("/tmp/output.txt", "a") as f:
            #    f.write("%s\n" % str(result))
            if not result:
                result = ''
            stream_content = {'name': 'stdout', 'text': str(result)}
            self.send_response(self.iopub_socket, 'stream', stream_content)

        return {
            'status': 'ok',
            # The base class increments the execution count
            'execution_count': self.execution_count,
            'payload': [],
            'user_expressions': {},
        }
Beispiel #17
0
    def load(self, filepath):
        self.towninfoDict.clear()

        luafile = open(filepath, 'r', encoding='latin1')
        content = luafile.read()
        luafile.close()

        lua = LuaRuntime(unpack_returned_tuples=True)
        lua.execute(content)
        g = lua.globals()

        for mapname in list(g.mapNPCInfoTable):
            self.towninfoDict[mapname] = []
            for tagid in list(g.mapNPCInfoTable[mapname]):
                singleItem = LeeTowninfoSingleItem(
                    tagname=g.mapNPCInfoTable[mapname][tagid]['name'],
                    gbkname=g.mapNPCInfoTable[mapname][tagid]['name'].encode(
                        'latin1').decode('gbk'),
                    x=g.mapNPCInfoTable[mapname][tagid]['X'],
                    y=g.mapNPCInfoTable[mapname][tagid]['Y'],
                    tagtype=g.mapNPCInfoTable[mapname][tagid]['TYPE'])
                self.towninfoDict[mapname].append(singleItem)
Beispiel #18
0
    def process_rockspec(self, rsname):
        source = None
        rock_def = {}
        try:
            with open(rsname, 'r') as fh:
                source = fh.read()
        except Exception as e:
            return self.severe('failed to open/read rockspec: %s' % repr(e))
        lr = LuaRuntime()
        try:
            lr.execute(source)
            _G = lr.globals()
            rock_def['package'] = _G['package']
            rock_def['version'] = _G['version']
            rock_def['source'] = dict(_G['source'])
            rock_def['description'] = dict(_G['description'])
        except Exception as e:
            return self.severe('failed process rockspec: %s' % repr(e))

        rock = wp_rock()
        rock.defs = rock_def
        rock.filename = os.path.basename(rsname)
        return rock
Beispiel #19
0
    def load(self, filepath):
        self.itemInfoDict.clear()

        try:
            luafile = open(filepath, 'r', encoding = 'latin1')
            content = luafile.read()
            luafile.close()

            lua = LuaRuntime(unpack_returned_tuples=True)
            lua.execute(content)
            g = lua.globals()
        except Exception as _err:
            print('解析文件时发生了错误: %s' % filepath)
            raise

        for itemID in list(g.tbl):
            try:
                singleItem = LeeIteminfoSingleItem(
                    itemID = itemID,
                    unidentifiedDisplayName = g.tbl[itemID]['unidentifiedDisplayName'],
                    unidentifiedResourceName = g.tbl[itemID]['unidentifiedResourceName'],
                    unidentifiedDescriptionName = self.__normdesc(
                        g.tbl[itemID]['unidentifiedDescriptionName']
                    ),
                    identifiedDisplayName = g.tbl[itemID]['identifiedDisplayName'],
                    identifiedResourceName = g.tbl[itemID]['identifiedResourceName'],
                    identifiedDescriptionName = self.__normdesc(
                        g.tbl[itemID]['identifiedDescriptionName']
                    ),
                    slotCount = g.tbl[itemID]['slotCount'],
                    ClassNum = g.tbl[itemID]['ClassNum'],
                )
                self.itemInfoDict[self.leeCommon.atoi(itemID)] = singleItem
            except Exception as _err:
                print('Error Item ID = %d' % itemID)
                raise
Beispiel #20
0
def load_lua_table(path, key_type=int):
    with open(path, encoding='utf-8') as f:
        s = f.read()

        m = re.search('_G.pg.([a-z_]+)', s)
        if m:
            table_name = m.group(1)

            s = 'pg = {}\npg.' + table_name + '= {}\n' + re.sub('_G.', '', s)
            s = re.sub('if rawget.*', '', s, flags=re.DOTALL)

        if s[0] == '{':
            s = 'pg = pg or {}\npg.data = ' + s

        s = re.sub('Vector3\((.*?)\)', '{\g<1>}', s)
        s = re.sub('AspectMode\.[A-Za-z]+', '"\g<0>"', s)
        s = re.sub('function \\(\\)', '', s)
        s = re.sub('end\\(\\)', '', s)
        s = re.sub('uv0', 'pg', s)
        lua = LuaRuntime(unpack_returned_tuples=True)
        lua.execute(s)
        g = lua.globals()
        for value in g.pg.values():
            return convert_lua_to_python_dict(value, key_type)
Beispiel #21
0
            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)
Beispiel #22
0

# Load Lua sandbox code.
lua_sandbox = open("lua/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")(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)
Beispiel #23
0
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
Beispiel #24
0
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']
Beispiel #25
0
    def __init__(self, bot):
        super().__init__(bot)

        self.lua = LuaRuntime(unpack_returned_tuples=True)

        self.mp_pool = ProcessPoolExecutor(max_workers=4)
Beispiel #26
0
def get_lua_runtime():
    from lupa import LuaRuntime
    global LUA_RUNTIME  # pylint: disable=global-statement
    if LUA_RUNTIME is None:
        LUA_RUNTIME = LuaRuntime()
    return LUA_RUNTIME
Beispiel #27
0
 def get_label_for_problem(self):
     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 or self.format.get_contest_problem_label_script())
Beispiel #28
0
# HotFix: don't throw errors when LUA is getting an unknown key
def attr_getter(obj, name):
    if name in obj:
        if name in ['Blockable', 'HPCount', 'ReinforceArmor', 'TranscendArmor', 'ReinforceWeapon', 'TranscendWeapon']:
            return int(obj[name])
        else:
            return obj[name]
    return 0


def attr_setter(obj, name, value):
    obj[name] = value


lua = LuaRuntime(attribute_handlers=(attr_getter, attr_setter), unpack_returned_tuples=True)

LUA_OVERRIDE = [
    'function GET_ITEM_LEVEL(item) return 0 end',  # We cant emulate this function as geItemTable is undefined
    'function IsBuffApplied(pc, buff) return "NO" end',
    'function IsServerSection(pc) return 0 end',
    'function GetExProp(entity, name) return entity[name] end',
    'function GetExProp_Str(entity, name) return tostring(entity[name]) end',
    'function GetIESID(item) end',
    'function GetItemOwner(item) return {} end',
    'function GetOwner(monster) end',
    'function GetServerNation() end',
    'function GetServerGroupID() end',
    'function IsPVPServer(itemOwner) end',
    'function IMCRandom(min, max) return 0 end',
    'function ScpArgMsg(a, b, c) return "" end',
Beispiel #29
0
    def __init__(
            self,
            *,
            allow_global_state=True,  # TODO not yet fully implemented
            allow_random=True,
            allow_time=True,
            custom_globals=None,
            **kwargs):
        """Initialize a sandboxed LuaRuntime.

        Optional keyword arguments:
        - `allow_global_state` -- bool; whether to allow setting global
          variables and setting external variables from within a closure
          [closures NYI]
        - `allow_random` -- bool; whether to give access to Lua's PRNG functions
        - `allow_time` -- bool; whether to give access to Lua's date/time
          functions
        - `custom_globals` -- dict; any extra variables to insert into the
          global namespace

        All other args and kwargs are passed to LuaRuntime(). It is not
        necessary to pass `register_eval=False` or `register_builtins=False`,
        since this is already done by LuaSandbox.
        """
        self._allow_global_state = allow_global_state
        # Prevent access to Python from Lua.
        self._lua = LuaRuntime(register_eval=False,
                               register_builtins=False,
                               **kwargs)
        # Get the behind-the-scenes global table.
        allowed_names = LUA_SAFE_NAMES
        if allow_random:
            allowed_names += LUA_RANDOM_NAMES
        if allow_time:
            allowed_names += LUA_TIME_NAMES
        new_globals = {}
        for name in allowed_names:
            # We have to handle names like `string.format` by making a new table
            # `string` containing keys like `format`.
            t = new_globals
            keys = name.split('.')
            for key in keys[:-1]:
                if key not in t:
                    t[key] = self.table()
                t = t[key]
            t[keys[-1]] = self._lua.eval(name)
        if custom_globals:
            new_globals.update(custom_globals)
        new_globals = self.table_from(new_globals)
        # Override global table access if necessary.
        self._sandboxer_code = ''
        if not allow_global_state:
            new_globals = lua_utils.make_table_readonly_recursive(
                self, new_globals,
                "Cannot set value '%s' on %s; global variables are forbidden")
        self.globals().safe_globals = new_globals
        if self.globals().setfenv:
            # Lua 5.1
            self._sandboxer_code = 'setfenv(1, safe_globals)\n'
        else:
            # Lua 5.2+
            self._sandboxer_code = '_ENV = safe_globals\n'
Beispiel #30
0
 def __init__(self, umka):
     self.umka = umka
     self.lua = LuaRuntime(unpack_returned_tuples=True)