TIPS:关于使用矩阵的加减乘除测试C++与Lua的交互以及下面没讲述到的知识点可以阅读第一版:
https://blog.csdn.net/qq135595696/article/details/128960951
同时下面两个方式矩阵的数据都来源于C++端,只是第一种是在C++端进行结果比较展示,第二种方式(userdata)是在lua端进行结果比较展示。
下面C++端引入第三方开源库测试lua端矩阵的运算是否正确,参考链接如下:
http://eigen.tuxfamily.org/index.php?title=3.4
#include <iostream>
#include <vector>
#include <assert.h>
#include <Dense>
#include "lua.hpp"
using std::cout;
using std::endl;
using std::cin;
static int gs_Top = 0;
#define STACK_NUM(L) \
gs_Top = lua_gettop(L); \
std::cout<<"stack top:"<< gs_Top <<std::endl\
// 矩阵运算
enum class MATRIX_OPERATE {
ADD,
SUB,
MUL,
DIV,
NONE
};
#define LUA_SCRIPT_PATH "matrix2.0.lua"
static std::vector<std::vector<double>> gs_mat1;
static std::vector<std::vector<double>> gs_mat2;
static bool OutPrint(const std::vector<std::vector<double>>& data) {
for (int32_t i = 0; i < data.size(); i++) {
for (int32_t j = 0; j < data[0].size(); j++)
std::cout << " "<< data[i][j];
std::cout << '\n';
}
std::cout << "......\n";
return true;
}
static bool Init(lua_State* L) {
assert(NULL != L);
gs_mat1.clear();
gs_mat2.clear();
if (luaL_dofile(L, LUA_SCRIPT_PATH)) {
printf("%s\n", lua_tostring(L, -1));
return false;
}
return true;
}
static bool CreateLuaArr(lua_State* L, const std::vector<std::vector<double>>& data) {
assert(NULL != L);
//STACK_NUM(L);
lua_newtable(L);
for (int32_t i = 0; i < data.size(); i++) {
lua_newtable(L);
for (int32_t j = 0; j < data[0].size(); j++) {
lua_pushnumber(L, data[i][j]);
lua_rawseti(L, -2, j + 1);
}
lua_rawseti(L, -2, i + 1);
}
//STACK_NUM(L);
return true;
}
static bool GetLuaArr(lua_State* L, std::vector<std::vector<double>>& outData) {
assert(NULL != L);
outData.clear();
bool result = false;
int32_t row = 0;
int32_t col = 0;
if (LUA_TTABLE != lua_type(L, -1)) {
goto Exit;
}
if (LUA_TTABLE != lua_getfield(L, -1, "tbData")) {
goto Exit;
}
lua_getfield(L, -2, "nRow");
row = lua_tointeger(L, -1);
lua_pop(L, 1);
lua_getfield(L, -2, "nColumn");
col = lua_tointeger(L, -1);
lua_pop(L, 1);
for (int32_t i = 0; i < row; i++) {
lua_rawgeti(L, -1, i + 1);
std::vector<double> data;
for (int32_t j = 0; j < col; j++) {
lua_rawgeti(L, -1, j + 1);
data.push_back(lua_tonumber(L, -1));
lua_pop(L, 1);
}
outData.push_back(data);
lua_pop(L, 1);
}
//维持lua堆栈平衡
lua_pop(L, 1);
result = true;
Exit:
return true;
}
static bool MatrixOperate(lua_State* L,
std::vector<std::vector<double>>& outData, MATRIX_OPERATE type) {
outData.clear();
const char* funcName = NULL;
bool result = false;
switch (type) {
case MATRIX_OPERATE::ADD:
funcName = "MatrixAdd";
break;
case MATRIX_OPERATE::SUB:
funcName = "MatrixSub";
break;
case MATRIX_OPERATE::MUL:
funcName = "MatrixMul";
break;
case MATRIX_OPERATE::DIV:
funcName = "MatrixDiv";
break;
case MATRIX_OPERATE::NONE:
break;
default:
break;
}
lua_getglobal(L, funcName);
luaL_checktype(L, -1, LUA_TFUNCTION);
//添加形参
CreateLuaArr(L, gs_mat1);
CreateLuaArr(L, gs_mat2);
//调用函数
if (lua_pcall(L, 2, 1, 0)) {
printf("error[%s]\n", lua_tostring(L, -1));
goto Exit;
}
GetLuaArr(L, outData);
result = true;
Exit:
return result;
}
static bool APIMatrixOperate(const std::vector<std::vector<double>>& data1,
const std::vector<std::vector<double>>& data2, MATRIX_OPERATE type, Eigen::MatrixXd& outResMat) {
Eigen::MatrixXd mat1(data1.size(), data1[0].size());
Eigen::MatrixXd mat2(data2.size(), data2[0].size());
for (int i = 0; i < data1.size(); i++) {
for (int j = 0; j < data1[0].size(); j++) {
mat1(i, j) = data1[i][j];
}
}
for (int i = 0; i < data2.size(); i++) {
for (int j = 0; j < data2[0].size(); j++) {
mat2(i, j) = data2[i][j];
}
}
switch (type) {
case MATRIX_OPERATE::ADD:
outResMat = mat1 + mat2;
break;
case MATRIX_OPERATE::SUB:
outResMat = mat1 - mat2;
break;
case MATRIX_OPERATE::MUL:
outResMat = mat1 * mat2;
break;
case MATRIX_OPERATE::DIV:
outResMat = mat1 * (mat2.inverse());
break;
case MATRIX_OPERATE::NONE:
break;
default:
break;
}
return true;
}
static bool Run(lua_State* L) {
assert(NULL != L);
std::vector<std::vector<double>> addData;
std::vector<std::vector<double>> subData;
std::vector<std::vector<double>> mulData;
std::vector<std::vector<double>> divData;
Eigen::MatrixXd addApiData;
Eigen::MatrixXd subApiData;
Eigen::MatrixXd mulApiData;
Eigen::MatrixXd divApiData;
// 运算
gs_mat1 = { { 1,2,3 }, { 4,5,6 } };
gs_mat2 = { { 2,3,4 }, { 5,6,7 } };
MatrixOperate(L, addData, MATRIX_OPERATE::ADD);
APIMatrixOperate(gs_mat1, gs_mat2, MATRIX_OPERATE::ADD, addApiData);
gs_mat1 = addData;
gs_mat2 = { {1,1,1},{1,1,1} };
MatrixOperate(L, subData, MATRIX_OPERATE::SUB);
APIMatrixOperate(gs_mat1, gs_mat2, MATRIX_OPERATE::SUB, subApiData);
gs_mat1 = { {1,2,3},{4,5,6} };
gs_mat2 = { {7,8},{9,10},{11,12} };
MatrixOperate(L, mulData, MATRIX_OPERATE::MUL);
APIMatrixOperate(gs_mat1, gs_mat2, MATRIX_OPERATE::MUL, mulApiData);
gs_mat1 = { {41,2,3},{424,5,6},{742,8,11} };
gs_mat2 = { {1,2,1},{1,1,2},{2,1,1} };
MatrixOperate(L, divData, MATRIX_OPERATE::DIV);
APIMatrixOperate(gs_mat1, gs_mat2, MATRIX_OPERATE::DIV, divApiData);
// 输出
cout << "================加法:================" << endl;
OutPrint(addData);
cout << "正确答案:\n" << addApiData << endl;
cout << "================减法:================" << endl;
OutPrint(subData);
cout << "正确答案:\n" << subApiData << endl;
cout << "================乘法:================" << endl;
OutPrint(mulData);
cout << "正确答案:\n" << mulApiData << endl;
cout << "================除法:================" << endl;
OutPrint(divData);
cout << "正确答案:\n" << divApiData << endl;
return true;
}
static bool UnInit() {
return true;
}
int main020811() {
lua_State* L = luaL_newstate();
luaL_openlibs(L);
if (Init(L)) {
Run(L);
}
UnInit();
lua_close(L);
return 0;
}
local _class = {}
function class(super)
local tbClassType = {}
tbClassType.Ctor = false
tbClassType.super = super
tbClassType.New = function(...)
local tbObj = {}
do
local funcCreate
funcCreate = function(tbClass,...)
if tbClass.super then
funcCreate(tbClass.super,...)
end
if tbClass.Ctor then
tbClass.Ctor(tbObj,...)
end
end
funcCreate(tbClassType,...)
end
-- 防止调用Ctor初始化时,在Ctor内部设置了元表的情况发生
if getmetatable(tbObj) then
getmetatable(tbObj).__index = _class[tbClassType]
else
setmetatable(tbObj, { __index = _class[tbClassType] })
end
return tbObj
end
local vtbl = {}
_class[tbClassType] = vtbl
setmetatable(tbClassType, { __newindex =
function(tb,k,v)
vtbl[k] = v
end
})
if super then
setmetatable(vtbl, { __index =
function(tb,k)
local varRet = _class[super][k]
vtbl[k] = varRet
return varRet
end
})
end
return tbClassType
end
Matrix = class()
function Matrix:Ctor(data)
self.tbData = data
self.nRow = #data
if self.nRow > 0 then
self.nColumn = (#data[1])
else
self.nColumn = 0
end
-- print("row:",self.nRow," col:",self.nColumn)
setmetatable(self,{
__add = function(tbSource, tbDest)
assert(tbSource,"tbSource not exist")
assert(tbDest, "tbDest not exist")
local tbRes = Matrix.New({})
-- print(tbSource,tbDest)
-- print("tbSource:",tbSource.nRow,tbSource.nColumn)
-- tbSource:Print()
-- print("tbDest:",tbDest.nRow,tbDest.nColumn)
-- tbDest:Print()
if tbSource.nRow ~= tbDest.nRow
or tbSource.nColumn ~= tbDest.nColumn then
print("row or column not equal...")
return tbRes
else
for rowKey,rowValue in ipairs(tbSource.tbData) do
for colKey,colValue in ipairs(tbSource.tbData[rowKey]) do
if tbRes.tbData[rowKey] == nil then
tbRes.tbData[rowKey] = {}
end
if tbRes.tbData[rowKey][colKey] == nil then
tbRes.tbData[rowKey][colKey] = 0
end
tbRes.tbData[rowKey][colKey] =
tbSource.tbData[rowKey][colKey] + tbDest.tbData[rowKey][colKey]
end
end
tbRes.nRow = tbSource.nRow
tbRes.nColumn = tbSource.nColumn
return tbRes
end
end,
__sub = function(tbSource, tbDest)
assert(tbSource,"tbSource not exist")
assert(tbDest, "tbDest not exist")
local tbRes = Matrix.New({})
if tbSource.nRow ~= tbDest.nRow
or tbSource.nColumn ~= tbDest.nColumn then
print("row or column not equal...")
return tbRes
else
for rowKey,rowValue in ipairs(tbSource.tbData) do
for colKey,colValue in ipairs(tbSource.tbData[rowKey]) do
if tbRes.tbData[rowKey] == nil then
tbRes.tbData[rowKey] = {}
end
if tbRes.tbData[rowKey][colKey] == nil then
tbRes.tbData[rowKey][colKey] = 0
end
tbRes.tbData[rowKey][colKey] =
tbSource.tbData[rowKey][colKey] - tbDest.tbData[rowKey][colKey]
end
end
tbRes.nRow = tbSource.nRow
tbRes.nColumn = tbSource.nColumn
return tbRes
end
end,
__mul = function(tbSource, tbDest)
return self:_MartixMul(tbSource, tbDest)
end,
__div = function(tbSource, tbDest)
assert(tbSource,"tbSource not exist")
assert(tbDest, "tbDest not exist")
local nDet = self:_GetDetValue(tbDest)
if nDet == 0 then
print("matrix no inverse matrix...")
return nil
end
-- print("det ",nDet)
local tbInverseDest = self:_MatrixNumMul(self:_GetCompanyMatrix(tbDest), 1 / nDet)
-- self:_GetCompanyMatrix(tbDest):Print()
-- print(nDet)
-- tbInverseDest:Print()
return self:_MartixMul(tbSource, tbInverseDest)
end
}
)
end
function Matrix:Print()
for rowKey,rowValue in ipairs(self.tbData) do
for colKey,colValue in ipairs(self.tbData[rowKey]) do
io.write(self.tbData[rowKey][colKey],',')
end
print('')
end
end
-- 加
function Matrix:Add(matrix)
return self + matrix
end
-- 减
function Matrix:Sub(matrix)
return self - matrix
end
-- 乘
function Matrix:Mul(matrix)
return self * matrix
end
-- 除
function Matrix:Div(matrix)
return self / matrix
end
-- 切割,切去第rowIndex以及第colIndex列
function Matrix:_CutoffMatrix(tbMatrix, rowIndex, colIndex)
assert(tbMatrix,"tbMatrix not exist")
assert(rowIndex >= 1,"rowIndex < 1")
assert(colIndex >= 1,"colIndex < 1")
local tbRes = Matrix.New({})
tbRes.nRow = tbMatrix.nRow - 1
tbRes.nColumn = tbMatrix.nColumn - 1
for i = 1, tbMatrix.nRow - 1 do
for j = 1, tbMatrix.nColumn - 1 do
if tbRes.tbData[i] == nil then
tbRes.tbData[i] = {}
end
local nRowDir = 0
local nColDir = 0
if i >= rowIndex then
nRowDir = 1
end
if j >= colIndex then
nColDir = 1
end
tbRes.tbData[i][j] = tbMatrix.tbData[i + nRowDir][j + nColDir]
end
end
return tbRes
end
-- 获取矩阵的行列式对应的值
function Matrix:_GetDetValue(tbMatrix)
assert(tbMatrix,"tbMatrix not exist")
-- 当矩阵为一阶矩阵时,直接返回A中唯一的元素
if tbMatrix.nRow == 1 then
return tbMatrix.tbData[1][1]
end
local nAns = 0
for i = 1, tbMatrix.nColumn do
local nFlag = -1
if i % 2 ~= 0 then
nFlag = 1
end
nAns =
nAns + tbMatrix.tbData[1][i] *
self:_GetDetValue(self:_CutoffMatrix(tbMatrix, 1, i)) * nFlag
-- print("_GetDetValue nflag:",nFlag)
end
return nAns
end
-- 获取矩阵的伴随矩阵
function Matrix:_GetCompanyMatrix(tbMatrix)
assert(tbMatrix,"tbMatrix not exist")
local tbRes = Matrix.New({})
-- 伴随矩阵与原矩阵存在转置关系
tbRes.nRow = tbMatrix.nColumn
tbRes.nColumn = tbMatrix.nRow
for i = 1, tbMatrix.nRow do
for j = 1, tbMatrix.nColumn do
local nFlag = 1
if ((i + j) % 2) ~= 0 then
nFlag = -1
end
if tbRes.tbData[j] == nil then
tbRes.tbData[j] = {}
end
-- print(Matrix:_GetDetValue(Matrix:_CutoffMatrix(tbMatrix, i, j)))
-- Matrix:_CutoffMatrix(tbMatrix, i, j):Print()
-- print("---11----")
tbRes.tbData[j][i] =
self:_GetDetValue(self:_CutoffMatrix(tbMatrix, i, j)) * nFlag
end
end
return tbRes
end
-- 矩阵数乘
function Matrix:_MatrixNumMul(tbMatrix, num)
for i = 1, tbMatrix.nRow do
for j = 1, tbMatrix.nColumn do
tbMatrix.tbData[i][j] = tbMatrix.tbData[i][j] * num
end
end
return tbMatrix
end
-- 矩阵相乘
function Matrix:_MartixMul(tbSource, tbDest)
assert(tbSource,"tbSource not exist")
assert(tbDest, "tbDest not exist")
if tbSource.nColumn ~= tbDest.nRow then
print("column not equal row...")
return tbSource
else
local tbRes = Matrix.New({})
for i = 1, tbSource.nRow do
for j = 1, tbDest.nColumn do
if tbRes.tbData[i] == nil then
tbRes.tbData[i] = {}
end
if tbRes.tbData[i][j] == nil then
tbRes.tbData[i][j] = 0
end
for k = 1, tbSource.nColumn do
tbRes.tbData[i][j] =
tbRes.tbData[i][j] + (tbSource.tbData[i][k] * tbDest.tbData[k][j])
end
end
end
tbRes.nRow = tbSource.nRow
tbRes.nColumn = tbDest.nColumn
return tbRes
end
end
-- add
function MatrixAdd(data1, data2)
assert(data1,"data1 not exist")
assert(data2,"data2 not exist")
local matrix1 = Matrix.New(data1)
local matrix2 = Matrix.New(data2)
return matrix1 + matrix2
end
-- sub
function MatrixSub(data1, data2)
assert(data1,"data1 not exist")
assert(data2,"data2 not exist")
local matrix1 = Matrix.New(data1)
local matrix2 = Matrix.New(data2)
return matrix1 - matrix2
end
-- mul
function MatrixMul(data1, data2)
assert(data1,"data1 not exist")
assert(data2,"data2 not exist")
local matrix1 = Matrix.New(data1)
local matrix2 = Matrix.New(data2)
return matrix1 * matrix2
end
-- div
function MatrixDiv(data1, data2)
assert(data1,"data1 not exist")
assert(data2,"data2 not exist")
local matrix1 = Matrix.New(data1)
local matrix2 = Matrix.New(data2)
return matrix1 / matrix2
end

#include <iostream>
#include <Dense>
#include <vector>
#include "lua.hpp"
using std::cout;
using std::endl;
using std::cin;
#define CPP_MATRIX "CPP_MATRIX"
#define LUA_SCRIPT_PATH "matrix2.0-lua.lua"
static int gs_Top = 0;
#define STACK_NUM(L) \
gs_Top = lua_gettop(L); \
std::cout<<"stack top:"<< gs_Top <<std::endl\
// 矩阵运算
enum class MATRIX_OPERATE {
ADD,
SUB,
MUL,
DIV,
NONE
};
static std::vector<std::vector<double>> gs_mat1;
static std::vector<std::vector<double>> gs_mat2;
extern "C" {
static int CreateMatrix(lua_State* L) {
Eigen::MatrixXd** pp =
(Eigen::MatrixXd**)lua_newuserdata(L, sizeof(Eigen::MatrixXd*));
*pp = new Eigen::MatrixXd();
luaL_setmetatable(L, CPP_MATRIX);
return 1;
}
static int InitMatrix(lua_State* L) {
assert(NULL != L);
int32_t row = 0;
int32_t col = 0;
row = luaL_len(L, -1);
lua_rawgeti(L, -1, 1);
col = luaL_len(L, -1);
lua_pop(L, 1);
Eigen::MatrixXd** pp =
(Eigen::MatrixXd**)luaL_checkudata(L, 1, CPP_MATRIX);
(*pp)->resize(row, col);
for (int32_t i = 0; i < row; i++) {
lua_rawgeti(L, -1, i + 1);
for (int32_t j = 0; j < col; j++) {
lua_rawgeti(L, -1, j + 1);
(**pp)(i, j) = lua_tonumber(L, -1);
lua_pop(L, 1);
}
lua_pop(L, 1);
}
lua_pop(L, 2);
return 0;
}
static int UnInitMatrix(lua_State* L) {
Eigen::MatrixXd** pp =
(Eigen::MatrixXd**)luaL_checkudata(L, 1, CPP_MATRIX);
std::cout << "auto gc" << std::endl;
if (*pp) {
delete *pp;
}
return 0;
}
static int AddMatrix(lua_State* L) {
//STACK_NUM(L);
Eigen::MatrixXd** pp1 =
(Eigen::MatrixXd**)luaL_checkudata(L, 1, CPP_MATRIX);
Eigen::MatrixXd** pp2 =
(Eigen::MatrixXd**)luaL_checkudata(L, 2, CPP_MATRIX);
Eigen::MatrixXd** pp =
(Eigen::MatrixXd**)lua_newuserdata(L, sizeof(Eigen::MatrixXd*));
*pp = new Eigen::MatrixXd(); //该部分内存由C++分配
**pp = (**pp1) + (**pp2);
luaL_setmetatable(L, CPP_MATRIX);
//STACK_NUM(L);
return 1;
}
static int SubMatrix(lua_State* L) {
//STACK_NUM(L);
Eigen::MatrixXd** pp1 =
(Eigen::MatrixXd**)luaL_checkudata(L, 1, CPP_MATRIX);
Eigen::MatrixXd** pp2 =
(Eigen::MatrixXd**)luaL_checkudata(L, 2, CPP_MATRIX);
Eigen::MatrixXd** pp =
(Eigen::MatrixXd**)lua_newuserdata(L, sizeof(Eigen::MatrixXd*));
*pp = new Eigen::MatrixXd(); //该部分内存由C++分配
**pp = (**pp1) - (**pp2);
luaL_setmetatable(L, CPP_MATRIX);
//STACK_NUM(L);
return 1;
}
static int MulMatrix(lua_State* L) {
//STACK_NUM(L);
Eigen::MatrixXd** pp1 =
(Eigen::MatrixXd**)luaL_checkudata(L, 1, CPP_MATRIX);
Eigen::MatrixXd** pp2 =
(Eigen::MatrixXd**)luaL_checkudata(L, 2, CPP_MATRIX);
Eigen::MatrixXd** pp =
(Eigen::MatrixXd**)lua_newuserdata(L, sizeof(Eigen::MatrixXd*));
*pp = new Eigen::MatrixXd(); //该部分内存由C++分配
**pp = (**pp1) * (**pp2);
luaL_setmetatable(L, CPP_MATRIX);
//STACK_NUM(L);
return 1;
}
static int DivMatrix(lua_State* L) {
//STACK_NUM(L);
Eigen::MatrixXd** pp1 =
(Eigen::MatrixXd**)luaL_checkudata(L, 1, CPP_MATRIX);
Eigen::MatrixXd** pp2 =
(Eigen::MatrixXd**)luaL_checkudata(L, 2, CPP_MATRIX);
Eigen::MatrixXd** pp =
(Eigen::MatrixXd**)lua_newuserdata(L, sizeof(Eigen::MatrixXd*));
*pp = new Eigen::MatrixXd(); //该部分内存由C++分配
**pp = (**pp1) * ((**pp2).inverse());
luaL_setmetatable(L, CPP_MATRIX);
//STACK_NUM(L);
return 1;
}
static int PrintMatrix(lua_State* L) {
Eigen::MatrixXd** pp =
(Eigen::MatrixXd**)luaL_checkudata(L, 1, CPP_MATRIX);
std::cout << "正确答案:\n" << **pp << std::endl;
return 0;
}
}
static const luaL_Reg MatrixFuncs[] = {
{"InitMatrix", InitMatrix },
{"__gc", UnInitMatrix},
{"__add", AddMatrix },
{"__sub", SubMatrix },
{"__mul", MulMatrix },
{"__div", DivMatrix },
{"PrintMatrix",PrintMatrix },
{NULL, NULL }
};
extern "C" {
static bool CreateMatrixMetaTable(lua_State* L) {
luaL_newmetatable(L, CPP_MATRIX);
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
luaL_setfuncs(L, MatrixFuncs, 0);
//STACK_NUM(L);
lua_pop(L, 1);
return true;
}
}
bool CreateLuaArr(lua_State* L, const std::vector<std::vector<double>>& data) {
assert(NULL != L);
//STACK_NUM(L);
lua_newtable(L);
for (int32_t i = 0; i < data.size(); i++) {
lua_newtable(L);
for (int32_t j = 0; j < data[0].size(); j++) {
lua_pushnumber(L, data[i][j]);
lua_rawseti(L, -2, j + 1);
}
lua_rawseti(L, -2, i + 1);
}
//STACK_NUM(L);
return true;
}
bool MatrixOperate(lua_State* L, MATRIX_OPERATE type) {
const char* funcName = NULL;
bool result = false;
switch (type) {
case MATRIX_OPERATE::ADD:
funcName = "MatrixAdd";
break;
case MATRIX_OPERATE::SUB:
funcName = "MatrixSub";
break;
case MATRIX_OPERATE::MUL:
funcName = "MatrixMul";
break;
case MATRIX_OPERATE::DIV:
funcName = "MatrixDiv";
break;
case MATRIX_OPERATE::NONE:
break;
default:
break;
}
lua_getglobal(L, funcName);
luaL_checktype(L, -1, LUA_TFUNCTION);
//添加形参
CreateLuaArr(L, gs_mat1);
CreateLuaArr(L, gs_mat2);
//调用函数
if (lua_pcall(L, 2, 0, 0)) {
printf("error[%s]\n", lua_tostring(L, -1));
goto Exit;
}
result = true;
Exit:
return result;
}
bool Init(lua_State *L) {
//构造一张全局元表,名为CPP_MATRIX
CreateMatrixMetaTable(L);
//注册第三方API构造对象方法
lua_pushcfunction(L, CreateMatrix);
lua_setglobal(L, "CreateMatrix");
if (luaL_dofile(L, LUA_SCRIPT_PATH)) {
printf("%s\n", lua_tostring(L, -1));
}
return true;
}
bool Run(lua_State* L) {
assert(NULL != L);
// 运算
gs_mat1 = { { 1,2,3 }, { 4,5,6 } };
gs_mat2 = { { 2,3,4 }, { 5,6,7 } };
MatrixOperate(L, MATRIX_OPERATE::ADD);
gs_mat1 = { { 1,2,3 }, { 4,5,6 } };
gs_mat2 = { { 1,1,1 }, { 1,1,1 } };
MatrixOperate(L, MATRIX_OPERATE::SUB);
gs_mat1 = { {1,2,3},{4,5,6} };
gs_mat2 = { {7,8},{9,10},{11,12} };
MatrixOperate(L, MATRIX_OPERATE::MUL);
gs_mat1 = { {41,2,3},{424,5,6},{742,8,11} };
gs_mat2 = { {1,2,1},{1,1,2},{2,1,1} };
MatrixOperate(L, MATRIX_OPERATE::DIV);
return true;
}
bool UnInit() {
return true;
}
int main() {
lua_State* L = luaL_newstate();
luaL_openlibs(L);
if (Init(L)) {
Run(L);
}
UnInit();
lua_close(L);
return 0;
}
local _class = {}
function class(super)
local tbClassType = {}
tbClassType.Ctor = false
tbClassType.super = super
tbClassType.New = function(...)
local tbObj = {}
do
local funcCreate
funcCreate = function(tbClass,...)
if tbClass.super then
funcCreate(tbClass.super,...)
end
if tbClass.Ctor then
tbClass.Ctor(tbObj,...)
end
end
funcCreate(tbClassType,...)
end
-- 防止调用Ctor初始化时,在Ctor内部设置了元表的情况发生
if getmetatable(tbObj) then
getmetatable(tbObj).__index = _class[tbClassType]
else
setmetatable(tbObj, { __index = _class[tbClassType] })
end
return tbObj
end
local vtbl = {}
_class[tbClassType] = vtbl
setmetatable(tbClassType, { __newindex =
function(tb,k,v)
vtbl[k] = v
end
})
if super then
setmetatable(vtbl, { __index =
function(tb,k)
local varRet = _class[super][k]
vtbl[k] = varRet
return varRet
end
})
end
return tbClassType
end
Matrix = class()
function Matrix:Ctor(data)
self.tbData = data
self.nRow = #data
if self.nRow > 0 then
self.nColumn = (#data[1])
else
self.nColumn = 0
end
-- print("row:",self.nRow," col:",self.nColumn)
setmetatable(self,{
__add = function(tbSource, tbDest)
assert(tbSource,"tbSource not exist")
assert(tbDest, "tbDest not exist")
local tbRes = Matrix.New({})
-- print(tbSource,tbDest)
-- print("tbSource:",tbSource.nRow,tbSource.nColumn)
-- tbSource:Print()
-- print("tbDest:",tbDest.nRow,tbDest.nColumn)
-- tbDest:Print()
if tbSource.nRow ~= tbDest.nRow
or tbSource.nColumn ~= tbDest.nColumn then
print("row or column not equal...")
return tbRes
else
for rowKey,rowValue in ipairs(tbSource.tbData) do
for colKey,colValue in ipairs(tbSource.tbData[rowKey]) do
if tbRes.tbData[rowKey] == nil then
tbRes.tbData[rowKey] = {}
end
if tbRes.tbData[rowKey][colKey] == nil then
tbRes.tbData[rowKey][colKey] = 0
end
tbRes.tbData[rowKey][colKey] =
tbSource.tbData[rowKey][colKey] + tbDest.tbData[rowKey][colKey]
end
end
tbRes.nRow = tbSource.nRow
tbRes.nColumn = tbSource.nColumn
return tbRes
end
end,
__sub = function(tbSource, tbDest)
assert(tbSource,"tbSource not exist")
assert(tbDest, "tbDest not exist")
local tbRes = Matrix.New({})
if tbSource.nRow ~= tbDest.nRow
or tbSource.nColumn ~= tbDest.nColumn then
print("row or column not equal...")
return tbRes
else
for rowKey,rowValue in ipairs(tbSource.tbData) do
for colKey,colValue in ipairs(tbSource.tbData[rowKey]) do
if tbRes.tbData[rowKey] == nil then
tbRes.tbData[rowKey] = {}
end
if tbRes.tbData[rowKey][colKey] == nil then
tbRes.tbData[rowKey][colKey] = 0
end
tbRes.tbData[rowKey][colKey] =
tbSource.tbData[rowKey][colKey] - tbDest.tbData[rowKey][colKey]
end
end
tbRes.nRow = tbSource.nRow
tbRes.nColumn = tbSource.nColumn
return tbRes
end
end,
__mul = function(tbSource, tbDest)
return self:_MartixMul(tbSource, tbDest)
end,
__div = function(tbSource, tbDest)
assert(tbSource,"tbSource not exist")
assert(tbDest, "tbDest not exist")
local nDet = self:_GetDetValue(tbDest)
if nDet == 0 then
print("matrix no inverse matrix...")
return nil
end
-- print("det ",nDet)
local tbInverseDest = self:_MatrixNumMul(self:_GetCompanyMatrix(tbDest), 1 / nDet)
-- self:_GetCompanyMatrix(tbDest):Print()
-- print(nDet)
-- tbInverseDest:Print()
return self:_MartixMul(tbSource, tbInverseDest)
end
}
)
end
function Matrix:Print()
for rowKey,rowValue in ipairs(self.tbData) do
for colKey,colValue in ipairs(self.tbData[rowKey]) do
io.write(self.tbData[rowKey][colKey],',')
end
print('')
end
end
-- 加
function Matrix:Add(matrix)
return self + matrix
end
-- 减
function Matrix:Sub(matrix)
return self - matrix
end
-- 乘
function Matrix:Mul(matrix)
return self * matrix
end
-- 除
function Matrix:Div(matrix)
return self / matrix
end
-- 切割,切去第rowIndex以及第colIndex列
function Matrix:_CutoffMatrix(tbMatrix, rowIndex, colIndex)
assert(tbMatrix,"tbMatrix not exist")
assert(rowIndex >= 1,"rowIndex < 1")
assert(colIndex >= 1,"colIndex < 1")
local tbRes = Matrix.New({})
tbRes.nRow = tbMatrix.nRow - 1
tbRes.nColumn = tbMatrix.nColumn - 1
for i = 1, tbMatrix.nRow - 1 do
for j = 1, tbMatrix.nColumn - 1 do
if tbRes.tbData[i] == nil then
tbRes.tbData[i] = {}
end
local nRowDir = 0
local nColDir = 0
if i >= rowIndex then
nRowDir = 1
end
if j >= colIndex then
nColDir = 1
end
tbRes.tbData[i][j] = tbMatrix.tbData[i + nRowDir][j + nColDir]
end
end
return tbRes
end
-- 获取矩阵的行列式对应的值
function Matrix:_GetDetValue(tbMatrix)
assert(tbMatrix,"tbMatrix not exist")
-- 当矩阵为一阶矩阵时,直接返回A中唯一的元素
if tbMatrix.nRow == 1 then
return tbMatrix.tbData[1][1]
end
local nAns = 0
for i = 1, tbMatrix.nColumn do
local nFlag = -1
if i % 2 ~= 0 then
nFlag = 1
end
nAns =
nAns + tbMatrix.tbData[1][i] *
self:_GetDetValue(self:_CutoffMatrix(tbMatrix, 1, i)) * nFlag
-- print("_GetDetValue nflag:",nFlag)
end
return nAns
end
-- 获取矩阵的伴随矩阵
function Matrix:_GetCompanyMatrix(tbMatrix)
assert(tbMatrix,"tbMatrix not exist")
local tbRes = Matrix.New({})
-- 伴随矩阵与原矩阵存在转置关系
tbRes.nRow = tbMatrix.nColumn
tbRes.nColumn = tbMatrix.nRow
for i = 1, tbMatrix.nRow do
for j = 1, tbMatrix.nColumn do
local nFlag = 1
if ((i + j) % 2) ~= 0 then
nFlag = -1
end
if tbRes.tbData[j] == nil then
tbRes.tbData[j] = {}
end
-- print(Matrix:_GetDetValue(Matrix:_CutoffMatrix(tbMatrix, i, j)))
-- Matrix:_CutoffMatrix(tbMatrix, i, j):Print()
-- print("---11----")
tbRes.tbData[j][i] =
self:_GetDetValue(self:_CutoffMatrix(tbMatrix, i, j)) * nFlag
end
end
return tbRes
end
-- 矩阵数乘
function Matrix:_MatrixNumMul(tbMatrix, num)
for i = 1, tbMatrix.nRow do
for j = 1, tbMatrix.nColumn do
tbMatrix.tbData[i][j] = tbMatrix.tbData[i][j] * num
end
end
return tbMatrix
end
-- 矩阵相乘
function Matrix:_MartixMul(tbSource, tbDest)
assert(tbSource,"tbSource not exist")
assert(tbDest, "tbDest not exist")
if tbSource.nColumn ~= tbDest.nRow then
print("column not equal row...")
return tbSource
else
local tbRes = Matrix.New({})
for i = 1, tbSource.nRow do
for j = 1, tbDest.nColumn do
if tbRes.tbData[i] == nil then
tbRes.tbData[i] = {}
end
if tbRes.tbData[i][j] == nil then
tbRes.tbData[i][j] = 0
end
for k = 1, tbSource.nColumn do
tbRes.tbData[i][j] =
tbRes.tbData[i][j] + (tbSource.tbData[i][k] * tbDest.tbData[k][j])
end
end
end
tbRes.nRow = tbSource.nRow
tbRes.nColumn = tbDest.nColumn
return tbRes
end
end
-- add
function MatrixAdd(data1, data2)
assert(data1,"data1 not exist")
assert(data2,"data2 not exist")
local matrix1 = Matrix.New(data1)
local matrix2 = Matrix.New(data2)
local matrix3 = matrix1 + matrix2
print("===========加法===========")
matrix3:Print()
local cppMatrix1 = CreateMatrix()
cppMatrix1:InitMatrix(data1)
local cppMatrix2 = CreateMatrix()
cppMatrix2:InitMatrix(data2)
local cppMatrix3 = cppMatrix1 + cppMatrix2
cppMatrix3:PrintMatrix()
end
-- sub
function MatrixSub(data1, data2)
assert(data1,"data1 not exist")
assert(data2,"data2 not exist")
local matrix1 = Matrix.New(data1)
local matrix2 = Matrix.New(data2)
local matrix3 = matrix1 - matrix2
print("===========减法===========")
matrix3:Print()
local cppMatrix1 = CreateMatrix()
cppMatrix1:InitMatrix(data1)
local cppMatrix2 = CreateMatrix()
cppMatrix2:InitMatrix(data2)
local cppMatrix3 = cppMatrix1 - cppMatrix2
cppMatrix3:PrintMatrix()
end
-- mul
function MatrixMul(data1, data2)
assert(data1,"data1 not exist")
assert(data2,"data2 not exist")
local matrix1 = Matrix.New(data1)
local matrix2 = Matrix.New(data2)
local matrix3 = matrix1 * matrix2
print("===========乘法===========")
matrix3:Print()
local cppMatrix1 = CreateMatrix()
cppMatrix1:InitMatrix(data1)
local cppMatrix2 = CreateMatrix()
cppMatrix2:InitMatrix(data2)
local cppMatrix3 = cppMatrix1 * cppMatrix2
cppMatrix3:PrintMatrix()
end
-- div
function MatrixDiv(data1, data2)
assert(data1,"data1 not exist")
assert(data2,"data2 not exist")
local matrix1 = Matrix.New(data1)
local matrix2 = Matrix.New(data2)
local matrix3 = matrix1 / matrix2
print("===========除法===========")
matrix3:Print()
local cppMatrix1 = CreateMatrix()
cppMatrix1:InitMatrix(data1)
local cppMatrix2 = CreateMatrix()
cppMatrix2:InitMatrix(data2)
local cppMatrix3 = cppMatrix1 / cppMatrix2
cppMatrix3:PrintMatrix()
end

我好像记得Lua有类似Ruby的method_missing的东西。还是我记错了? 最佳答案 表的metatable的__index和__newindex可以用于与Ruby的method_missing相同的效果。 关于ruby-难道Lua没有和Ruby的method_missing相媲美的东西吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/7732154/
我正在查看instance_variable_set的文档并看到给出的示例代码是这样做的:obj.instance_variable_set(:@instnc_var,"valuefortheinstancevariable")然后允许您在类的任何实例方法中以@instnc_var的形式访问该变量。我想知道为什么在@instnc_var之前需要一个冒号:。冒号有什么作用? 最佳答案 我的第一直觉是告诉你不要使用instance_variable_set除非你真的知道你用它做什么。它本质上是一种元编程工具或绕过实例变量可见性的黑客攻击
在我的应用程序中,我需要能够找到所有数字子字符串,然后扫描每个子字符串,找到第一个匹配范围(例如5到15之间)的子字符串,并将该实例替换为另一个字符串“X”。我的测试字符串s="1foo100bar10gee1"我的初始模式是1个或多个数字的任何字符串,例如,re=Regexp.new(/\d+/)matches=s.scan(re)给出["1","100","10","1"]如果我想用“X”替换第N个匹配项,并且只替换第N个匹配项,我该怎么做?例如,如果我想替换第三个匹配项“10”(匹配项[2]),我不能只说s[matches[2]]="X"因为它做了两次替换“1fooX0barXg
我在我的Rails项目中使用Pow和powifygem。现在我尝试升级我的ruby版本(从1.9.3到2.0.0,我使用RVM)当我切换ruby版本、安装所有gem依赖项时,我通过运行railss并访问localhost:3000确保该应用程序正常运行以前,我通过使用pow访问http://my_app.dev来浏览我的应用程序。升级后,由于错误Bundler::RubyVersionMismatch:YourRubyversionis1.9.3,butyourGemfilespecified2.0.0,此url不起作用我尝试过的:重新创建pow应用程序重启pow服务器更新战俘
我正在尝试修改当前依赖于定义为activeresource的gem:s.add_dependency"activeresource","~>3.0"为了让gem与Rails4一起工作,我需要扩展依赖关系以与activeresource的版本3或4一起工作。我不想简单地添加以下内容,因为它可能会在以后引起问题:s.add_dependency"activeresource",">=3.0"有没有办法指定可接受版本的列表?~>3.0还是~>4.0? 最佳答案 根据thedocumentation,如果你想要3到4之间的所有版本,你可以这
这可能是个愚蠢的问题。但是,我是一个新手......你怎么能在交互式rubyshell中有多行代码?好像你只能有一条长线。按回车键运行代码。无论如何我可以在不运行代码的情况下跳到下一行吗?再次抱歉,如果这是一个愚蠢的问题。谢谢。 最佳答案 这是一个例子:2.1.2:053>a=1=>12.1.2:054>b=2=>22.1.2:055>a+b=>32.1.2:056>ifa>b#Thecode‘if..."startsthedefinitionoftheconditionalstatement.2.1.2:057?>puts"f
我有一个正在构建的应用程序,我需要一个模型来创建另一个模型的实例。我希望每辆车都有4个轮胎。汽车模型classCar轮胎模型classTire但是,在make_tires内部有一个错误,如果我为Tire尝试它,则没有用于创建或新建的activerecord方法。当我检查轮胎时,它没有这些方法。我该如何补救?错误是这样的:未定义的方法'create'forActiveRecord::AttributeMethods::Serialization::Tire::Module我测试了两个环境:测试和开发,它们都因相同的错误而失败。 最佳答案
我正在处理旧代码的一部分。beforedoallow_any_instance_of(SportRateManager).toreceive(:create).and_return(true)endRubocop错误如下:Avoidstubbingusing'allow_any_instance_of'我读到了RuboCop::RSpec:AnyInstance我试着像下面那样改变它。由此beforedoallow_any_instance_of(SportRateManager).toreceive(:create).and_return(true)end对此:let(:sport_
如果我使用ruby版本2.5.1和Rails版本2.3.18会怎样?我有基于rails2.3.18和ruby1.9.2p320构建的rails应用程序,我只想升级ruby的版本,而不是rails,这可能吗?我必须面对哪些挑战? 最佳答案 GitHub维护apublicfork它有针对旧Rails版本的分支,有各种变化,它们一直在运行。有一段时间,他们在较新的Ruby版本上运行较旧的Rails版本,而不是最初支持的版本,因此您可能会发现一些关于需要向后移植的有用提示。不过,他们现在已经有几年没有使用2.3了,所以充其量只能让更
我安装了ruby版本管理器,并将RVM安装的ruby实现设置为默认值,这样'哪个ruby'显示'~/.rvm/ruby-1.8.6-p383/bin/ruby'但是当我在emacs中打开inf-ruby缓冲区时,它使用安装在/usr/bin中的ruby。有没有办法让emacs像shell一样尊重ruby的路径?谢谢! 最佳答案 我创建了一个emacs扩展来将rvm集成到emacs中。如果您有兴趣,可以在这里获取:http://github.com/senny/rvm.el