小编Nik*_*eng的帖子

如何在lua中实现只读表?

我写了一个例子.

 function readOnly(t)  
      local newTable = {}  
      local metaTable = {}  
      metaTable.__index = t  
      metaTable.__newindex = function(tbl, key, value)   error("Data cannot be changed!")   end  
      setmetatable(newTable, metaTable)  
      return newTable  
  end

 local tbl = {
    sex = {
        male = 1,
        female = 1,
    },
    identity = {
        police = 1,
        student = 2,
        doctor = {
            physician = 1,
            oculist = 2,
        }
    }
 } 

 local hold = readOnly(tbl)
 print(hold.sex)
 hold.sex = 2   --error
Run Code Online (Sandbox Code Playgroud)

这意味着我可以访问表"tbl"的字段,但同时,我无法更改与该字段相关的值.

现在,问题是我想让所有嵌套表拥有这个只读属性.如何改进"readOnly"方法?

lua readonly lua-table

3
推荐指数
1
解决办法
1052
查看次数

“编码不可知”的定义是什么?

在lua 5.3参考手册中,我们可以看到:

Lua 也是编码不可知的;它不对字符串的内容做任何假设。

我无法理解这句话说的是什么。

lua encoding

3
推荐指数
1
解决办法
582
查看次数

Lua中匿名函数的类型是什么?

在Lua参考手册中,它说每个值都有一个类型,可能是本地,全局,表字段类型之一.我的问题是Lua中匿名函数的类型是什么?匿名函数有什么生命周期?我只是举个例子.

local co = coroutine.create( function () print "hi" end )

print(coroutine.status(co))
Run Code Online (Sandbox Code Playgroud)

lua

2
推荐指数
1
解决办法
346
查看次数

关于C++中的复制控制

我定义了一个名为Student的类.

// Student.h
#pragma once
#include <iostream>
using namespace std;

class Student {
public:
    Student();
    Student(const Student &s);
    Student(int ii);
    Student& operator=(const Student &s);
    ~Student();
private:
    int i;
};

// Student.cpp
#include "Student.h"

Student::Student(): i(0)
{
    cout << "ctor" << endl;
}

Student::Student(const Student &s)
{
    i = s.i;
    cout << "copy constructor" << endl;
}

Student::Student(int ii): i(ii)
{
    cout << "Student(int ii)" <<  endl;
}

Student& Student::operator=(const Student &s)
{
    cout << "assignment operator" << endl;
    i = …
Run Code Online (Sandbox Code Playgroud)

c++ constructor

2
推荐指数
1
解决办法
565
查看次数

标签 统计

lua ×3

c++ ×1

constructor ×1

encoding ×1

lua-table ×1

readonly ×1