FunctionCall.h:
#include <sstream>
#include <string>
#include <vector>
// 函数调用
class FunctionCall
{
public:
FunctionCall();
~FunctionCall();
std::string call(const std::string &line);
private:
void parse(const std::string &line);
private:
void call0();
void call1();
void call2();
void call3();
void call4();
void call5();
private:
std::string funcname;
std::vector<std::string> args;
std::string result;
};
FunctionCall.cpp:
#include "FunctionCall.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
FunctionCall::FunctionCall() {}
FunctionCall::~FunctionCall() {}
void FunctionCall::parse(const std::string &line)
{
std::istringstream iss(line);
std::string tmp;
while (std::getline(iss, tmp, ',')) {
if (funcname.empty())
funcname = tmp;
else
args.emplace_back(tmp);
}
}
// 执行外部脚本
std::string FunctionCall::call(const std::string &line)
{
parse(line);
if(funcname.empty())
return "invalid function";
switch (args.size()) {
case 0: {
call0();
} break;
case 1: {
call1();
} break;
case 2: {
call2();
} break;
case 3: {
call3();
} break;
case 4: {
call4();
} break;
case 5: {
call5();
} break;
default: {
} break;
}
return result;
}
void FunctionCall::call0()
{
if("test" == funcname)
std::cout << "run test" << std::endl;
}
void FunctionCall::call1() {
}
void FunctionCall::call2() {
}
void FunctionCall::call3() {
}
void FunctionCall::call4() {
}
void FunctionCall::call5() {
}
LocalScriptFile.h:
#include <string>
class LocalScriptFile
{
public:
bool doFile(const char *path);
private:
bool jumpComment(const std::string &line);
void doScript(const std::string &line);
private:
bool m_isComment = false;
};
LocalScriptFile.cpp:
#include "LocalScriptFile.h"
#include "FunctionCall.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
bool LocalScriptFile::jumpComment(const std::string &line) {
if(m_isComment) {
if (-1 != line.find("**/"))
m_isComment = false;
return true;
} else{
if (-1 != line.find("/**"))
m_isComment = true;
return m_isComment;
}
}
bool LocalScriptFile::doFile(const char *path)
{
if (-1 != std::string(path).rfind(".lua")) {
std::ifstream file(path);
if (!file.is_open()) {
std::cerr << "Failed to open the file." << std::endl;
return false;
}
bool isComment = false;
std::string line;
while (std::getline(file, line)) {
// std::cout << "Read line: " << line << std::endl;
if(jumpComment(line))
continue;
doScript(line);
}
file.close();
return true;
}
return false;
}
// 执行外部脚本
void LocalScriptFile::doScript(const std::string &line)
{
FunctionCall call;
std::stringstream logStream;
logStream << call.call(line) << " = " << line;
}
test.lua
/*
测试脚本文件
*/
test
使用示例:
void main() {
PxxLocalScriptFile scriptFile;
if(scriptFile.doFile("test.lua"))
std::cout << "success" << std::endl;
}