各位大牛好,我刚刚接触qt不久。在使用qtscript时遇到个问题:
程序主体是一个串口调试工具,实现了简单的向串口设备发送和读取指令的功能。
我现在思考使用脚本来发送指令, 想法是:让C++程序来读入脚本文件,将脚本文件中的语句返回到C++程序中,再将语句指令发送给串口设备。这样做的好处是每次需要发送不同指令的话,我只用修改脚本文件就可以了。
但是目前遇到的问题就是:如何将脚本文件中的语句字符串返回给C++程序?
目前我暂时是这么做的:
C++程序中的脚本语言解析部分:
QScriptEngine engine;
QString scriptFileName(":/myscriptfile.js");// Change the script file according to the requirement.
QFile file(scriptFileName);
file.open(QIODevice::ReadOnly);
engine.evaluate(file.readAll(), scriptFileName);
file.close();
QScriptValue global = engine.globalObject();
QScriptValue GeneralCommand = global.property("myCommand");
QScriptValue ATCommand1 = global.property("Command1");
QScriptValue ATCommand2 = global.property("Command2");
QScriptValue ATCommand3 = global.property("Command3");
QScriptValue ATCommand4 = global.property("Command4");
QScriptValue ATCommand5 = global.property("Command5");
CommandString[0]=GeneralCommand.call(ATCommand1).toString();
CommandString[1]=GeneralCommand.call(ATCommand2).toString();
CommandString[2]=GeneralCommand.call(ATCommand3).toString();
CommandString[3]=GeneralCommand.call(ATCommand4).toString();
CommandString[4]=GeneralCommand.call(ATCommand5).toString();
对应的脚本文件myscriptfile.js是:
//! [0]
function myCommand() { return this.Command;}
Command1 = { Command: 'test command 1'}
Command2 = { Command: ' test command 2'}
Command3 = { Command: ' test command 3}
Command4 = { Command: ' test command 4'}
Command5 = { Command: ' test command 5'}b
//! [0]
目前这样做是可以实现,但是感觉不方便了,我在想更好的办法来写脚本,比如在脚本文件中这样写:
SendCommand('test command 1');
SendCommand('test command 2');
SendCommand('test command 3');
SendCommand('test command 4');
但是应该如何将'test command 1', 'test command 2', 'test command 3', 'test command 4'z这些字符串按顺序返回给C++程序,在C++中如何对应的去解析脚本,?
求各位给一个好办法了。谢谢。