我写了一个例子.
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 5.3参考手册中,我们可以看到:
Lua 也是编码不可知的;它不对字符串的内容做任何假设。
我无法理解这句话说的是什么。
在Lua参考手册中,它说每个值都有一个类型,可能是本地,全局,表字段类型之一.我的问题是Lua中匿名函数的类型是什么?匿名函数有什么生命周期?我只是举个例子.
local co = coroutine.create( function () print "hi" end )
print(coroutine.status(co))
Run Code Online (Sandbox Code Playgroud) 我定义了一个名为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)