aardio 元表的基本应用

axuanup 2月前 421

//aardio 元表
import console;

var tab1 = {10,20,30};	//普通表
var tab2 = {2};	//普通表

//给table设置个元表,相当于给table添加了一些行为
var meta = {
	_tostring = function() {
		//直接转为字符串
		return string.join(owner,",")
 	};
 	_tonumber = function() {
 		//直接转为数字
		return owner; 
 	};
	_eq = function(b){
		//等于==
		return owner[1] === b[1]; 
	};
	_le = function(b){
		//小于等于<=
		return owner[1] <= b[1]; 
	};
	_lt = function(b){
		//小于<
		return owner[1] < b[1]; 
	};
	_add = function(b){
		//加
		return owner[1] + b[1];
	};
	_sub = function(b){
		//减
		return owner[1] - b[1];
	};
	_mul = function(b){
		//乘
		return owner[1] * b[1];
	};
	_div = function(b){
		//除
		return owner[1] / b[1];
	};
 	_mod = function(b) {
 		//模
		return owner[1] % b[1]; 
 	};
 	_pow = function(b) {
 		//幂
		return owner[1] ** b[1]; 
 	};
 	_lshift = function(b) {
		//左移<<
		return owner[1] << b[1]; 
 	};
 	_rshift = function(b) {
		//右移>>
		return owner[1] >> b[1];
 	};
 	_unm = function() {
 		//取反
		return -owner[1]; 
 	};
 	_len = function() {
 		//取长度
		return #owner
 	};
 	_concat = function(b) {
 		//拼接
		return table.concat(owner,b); 
 	};
 	_call = function(a,b) {
 		//作为函数使用
		return a+b; 
 	};
}

tab1@ = meta;	//给table1添加元表
tab2@ = meta;	//给table2添加元表

var eq = tab1 == tab2;	//相等table元方法
var le1 = tab1 >= tab2;	//大于等于table元方法
var le2 = tab1 <= tab2;	//小于等于table元方法

var lt1 = tab1 > tab2;	//大于table元方法
var lt2 = tab1 < tab2;	//小于table元方法

var add = tab1 + tab2;	//加法table元方法
var sub = tab1 - tab2;	//减法table元方法
var mul = tab1 * tab2;	//乘法table元方法
var div = tab1 / tab2;	//除法table元方法
var mod = tab1 % tab2; 	//取模table元方法
var pow = tab1 ** tab2;	//取幂table元方法
var unm = -tab1
var concat = tab1++tab2;	//拼接table元方法
var lshift = tab1<<tab2;	//左移table元方法
var rshift = tab1>>tab2;	//右移table元方法
var len = #tab1         	//长度table元方法


console.log("tostring->",tostring(tab1))
console.log("tonumber->",tonumber(tab1))
console.log("等于 == eq->",eq)
console.log("大于等于 >=lt1->",lt1)
console.log("小于等于 <=lt2->",lt2)
console.log("大于 > le1->",le1)
console.log("小于 < le2->",le2)
console.log("加法 + add->",add)
console.log("减法 - sub->",sub)
console.log("乘法 * mul->",mul)
console.log("除法 / div->",div)
console.log("取模 % mod->",mod)
console.log("取幂 pow->",pow)
console.log("取反 unm->",unm)
console.log("长度 len->",len)
console.log("函数表 call->",tab1(20,40))
console.dump("拼接表 concat->",concat)
console.log("左移 lshift->",lshift)
console.log("右移 rshift->",rshift)

console.pause(true);

最新回复 (0)
返回