19.Lua调用CSharp-二维数组
19.1 知识点
准备工作
启动Lua脚本
LuaManager.Instance.Init();
LuaManager.Instance.DoLuaFile("Lesson19_Lua调用CSharp_二维数组");
定义有二维数组的测试类
public class Lesson19_Test
{
public int[,] array = new int[2, 3] { { 1, 2, 3 }, { 4, 5, 6 } };
public void SetValue(int[,] array, int value, int index1, int index2)
{
array[index1, index2] = value;
}
}
在Lua脚本实例化测试类
local test = CS.Lesson19_Test()
操作二维数组
获取行列长度
print("行:" .. test.array:GetLength(0))
print("列:" .. test.array:GetLength(1))
获取二维数组元素
-- 不能通过[0,0]或者[0][0]访问C#二维数组元素 Lua不支持这样的语法 会报错
-- 需要使用C#数组类的GetValue方法传入索引
print(test.array:GetValue(0,0)) -- 1
print(test.array:GetValue(1,0)) -- 4
遍历二维数组
for i=0,test.array:GetLength(0)-1 do
for j=0,test.array:GetLength(1)-1 do
print(test.array:GetValue(i,j)) -- 1 2 3 4 5 6
end
end
使用封装的设置二维数组元素方法
test:SetValue(test.array, 999, 0, 0)
print(test.array:GetValue(0,0)) -- 999
19.2 知识点代码
Lesson19_Lua调用CSharp_二维数组.lua
print('我是Lua脚本 Lesson19_Lua调用CSharp_二维数组')
local test = CS.Lesson19_Test()
print("**********知识点一 操作二维数组************")
--得到二维数组行列长度
print("行:" .. test.array:GetLength(0))
print("列:" .. test.array:GetLength(1))
--得到二维数组元素
--不能通过[0,0]或者[0][0]访问C#二维数组元素 Lua不支持这样的语法 会报错
--需要使用C#数组类的GetValue方法传入索引
print(test.array:GetValue(0,0))--1
print(test.array:GetValue(1,0))--4
--遍历二维数组
for i=0,test.array:GetLength(0)-1 do
for j=0,test.array:GetLength(1)-1 do
print(test.array:GetValue(i,j))--1 2 3 4 5 6
end
end
--使用自己在类中封装的设置二维数组元素方法
test:SetValue(test.array, 999, 0, 0)
print(test.array:GetValue(0,0))--999
Lesson19_Lua调用CSharp_二维数组
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Lesson19_Lua调用CSharp_二维数组 : MonoBehaviour
{
void Start()
{
LuaManager.Instance.Init();
LuaManager.Instance.DoLuaFile("Lesson19_Lua调用CSharp_二维数组");
}
}
public class Lesson19_Test
{
public int[,] array = new int[2, 3] { { 1, 2, 3 }, { 4, 5, 6 } };
public void SetValue(int[,] array, int value, int index1, int index2)
{
array[index1, index2] = value;
}
}
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 785293209@qq.com