Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import expression from 'angular-expressions';
import { stageStateManager } from '@/Core/Modules/stage/stageStateManager';
import { webgalStore } from '@/store/store';
import { logger } from '@/Core/util/logger';
import random from 'lodash/random';
import { WebGAL } from '@/Core/WebGAL';

/**
* 提取变量名和表达式
* @param expressionString 表达式字符串,例如 "x = a + 5"
* @returns 包含变量名和表达式,如果无效则返回 undefined
*/
export function extractVariableNameAndExpression(
expressionString: string,
): { variableName: string; expression: string } | undefined {
const equalIndex = expressionString.indexOf('=');
if (equalIndex === -1) {
return undefined;
}

const variableName = expressionString.substring(0, equalIndex).trim();
if (variableName.length === 0) {
return undefined;
}

const expression = expressionString.substring(equalIndex + 1).trim();
if (expression.length === 0) {
return undefined;
}

return { variableName, expression };
}

// 内置函数
const builtinFunctions = {
random: (...args: any[]) => {
return args.length ? random(...args) : Math.random();
},
};

/**
* 评估表达式字符串
* @param expressionString 表达式字符串
* @returns 评估结果,可能是 string、number、boolean 或 undefined
* 但也有可能返回其他类型,取决于表达式的内容和上下文
*/
export function evaluateExpression(expressionString: string): string | number | boolean | undefined {
try {
const evaluate = expression.compile(expressionString);

const stageState = stageStateManager.getCalculationStageState();
const stageVar = stageState.GameVar;
const userData = webgalStore.getState().userData;
const globalVar = userData.globalGameVar;

const scope: any = {};
// 先加入内置函数(最低优先级)
Object.assign(scope, builtinFunctions);
// 然后按查找链依次覆盖:全局变量 -> 舞台变量 -> 当前调用帧的局部变量(最高优先级)
Object.assign(scope, globalVar);
Object.assign(scope, stageVar);
Object.assign(scope, WebGAL.sceneManager.sceneData.currentLocals);
// 支持 $ 前缀的特殊值
scope['$stage'] = stageState;
scope['$userData'] = userData;

const result = evaluate(scope);
switch (typeof result) {
case 'string':
case 'number':
case 'boolean':
return result;
default:
logger.warn(`不支持的表达式求值类型: ${typeof result},表达式: ${expressionString}`);
return undefined;
}
} catch (error) {
logger.warn(`表达式求值失败: ${expressionString}`, error);
return undefined;
}
}
12 changes: 9 additions & 3 deletions packages/webgal/src/Core/controller/gamePlay/scriptExecutor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { runScript } from './runScript';
import { logger } from '../../util/logger';
import { returnFromScene } from '../scene/returnFromScene';
import { webgalStore } from '@/store/store';
import { getValueFromStateElseKey } from '@/Core/gameScripts/setVar';
import { legacyGetValueFromStateElseKey } from '@/Core/gameScripts/setVar';
import { strIf } from '@/Core/controller/gamePlay/strIf';
import cloneDeep from 'lodash/cloneDeep';
import { WebGAL } from '@/Core/WebGAL';
Expand All @@ -12,6 +12,7 @@ import { stageStateManager } from '@/Core/Modules/stage/stageStateManager';
import { jumpToLabel } from '@/Core/gameScripts/label/jumpToLabel';
import { prefetchCurrentSceneByProgress } from '@/Core/util/prefetcher/progressPrefetcher';
import { WEBGAL_NONE } from '@/Core/constants';
import { evaluateExpression } from '@/Core/controller/gamePlay/expressionEvaluation';

const MAX_FORWARD_SCRIPT_EXECUTION = 1000;

Expand All @@ -28,6 +29,11 @@ export const whenChecker = (whenValue: string | undefined): boolean => {
if (whenValue === undefined) {
return true;
}

if (!WebGAL.legacyExpressionParser) {
return Boolean(evaluateExpression(whenValue));
}

// 先把变量解析出来
const valExpArr = whenValue.split(/([+\-*\/()><!]|>=|<=|==|&&|\|\||!=)/g);
const valExp = valExpArr
Expand All @@ -37,7 +43,7 @@ export const whenChecker = (whenValue: string | undefined): boolean => {
if (e.match(/^(true|false)$/)) {
return e;
}
return getValueFromStateElseKey(e, true, true);
return legacyGetValueFromStateElseKey(e, true, true);
} else return e;
})
.reduce((pre, curr) => pre + curr, '');
Expand Down Expand Up @@ -77,7 +83,7 @@ export const scriptExecutor = (depth = 0, options: ScriptExecutionOptions = {})

if (contentExp !== null) {
contentExp.forEach((e) => {
const contentVarValue = getValueFromStateElseKey(e.replace(/(?<!\\)\{(.*)\}/, '$1'));
const contentVarValue = legacyGetValueFromStateElseKey(e.replace(/(?<!\\)\{(.*)\}/, '$1'));
retContent = retContent.replace(e, contentVarValue);
});
}
Expand Down
48 changes: 35 additions & 13 deletions packages/webgal/src/Core/gameScripts/setVar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import random from 'lodash/random';
import { getBooleanArgByKey } from '../util/getSentenceArg';
import { stageStateManager } from '@/Core/Modules/stage/stageStateManager';
import { WebGAL } from '@/Core/WebGAL';
import { evaluateExpression, extractVariableNameAndExpression } from '@/Core/controller/gamePlay/expressionEvaluation';

/**
* 变量的作用域,与查找链一一对应。
Expand Down Expand Up @@ -67,7 +68,13 @@ export const setGameVarFromExpression = ({
if (!normalizedKey) {
return;
}
setGameVar({ key: normalizedKey, value: resolveSetVarValue(value) }, scope);

const resolvedValue = resolveSetVarValue(value);
if (resolvedValue === undefined) {
return;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

此处应有 log

setGameVar({ key: normalizedKey, value: resolvedValue }, scope);

if (scope === 'global') {
logger.debug('设置全局变量:', {
key: normalizedKey,
Expand Down Expand Up @@ -95,10 +102,20 @@ export const setGameVarFromExpression = ({
*/
export const setVar = (sentence: ISentence): IPerform => {
const scope = resolveVarScope(sentence);
if (sentence.content.match(/\s*=\s*/)) {
const key = sentence.content.split(/\s*=\s*/)[0];
const valExp = sentence.content.split(/\s*=\s*/)[1];
setGameVarFromExpression({ key, value: valExp, scope });
if (WebGAL.legacyExpressionParser) {
if (sentence.content.match(/\s*=\s*/)) {
const key = sentence.content.split(/\s*=\s*/)[0];
const valExp = sentence.content.split(/\s*=\s*/)[1];
setGameVarFromExpression({ key, value: valExp, scope });
}
} else {
const extracted = extractVariableNameAndExpression(sentence.content);
if (extracted) {
const { variableName, expression } = extracted;
setGameVarFromExpression({ key: variableName, value: expression, scope });
} else {
logger.error(`setVar 语句格式错误,无法提取变量名和表达式: ${sentence.content}`);
}
}
return createNonePerform();
};
Expand All @@ -107,17 +124,22 @@ type BaseVal = string | number | boolean | undefined;

const hasOwn = (obj: object, key: string) => Object.prototype.hasOwnProperty.call(obj, key);

export function resolveSetVarValue(valExp: string): string | boolean | number {
export function resolveSetVarValue(valExp: string): string | boolean | number | undefined {
if (!WebGAL.legacyExpressionParser) {
// 空表达式(如不带返回值的 return)没有求值的必要,直接取空值,避免无谓的求值失败告警
return valExp.trim() ? evaluateExpression(valExp) : '';
}

if (/^\s*[a-zA-Z_$][\w$]*\s*\(.*\)\s*$/.test(valExp)) {
return EvaluateExpression(valExp);
return LegacyEvaluateExpression(valExp);
} else if (valExp.match(/[+\-*\/()]/)) {
const valExpArr = valExp.split(/([+\-*\/()])/g);
const valExp2 = valExpArr
.map((e) => {
if (!e.trim().match(/^[a-zA-Z_$][a-zA-Z0-9_.]*$/)) {
return e;
}
const _r = getValueFromStateElseKey(e.trim(), true);
const _r = legacyGetValueFromStateElseKey(e.trim(), true);
return typeof _r === 'string' ? `'${_r}'` : _r;
})
.reduce((pre, curr) => pre + curr, '');
Expand All @@ -142,7 +164,7 @@ export function resolveSetVarValue(valExp: string): string | boolean | number {
if (!isNaN(Number(valExp))) {
return Number(valExp);
} else {
return getValueFromStateElseKey(valExp, true) ?? '';
return legacyGetValueFromStateElseKey(valExp, true) ?? '';
}
}
return '';
Expand All @@ -151,7 +173,7 @@ export function resolveSetVarValue(valExp: string): string | boolean | number {
/**
* 执行函数
*/
function EvaluateExpression(val: string) {
function LegacyEvaluateExpression(val: string) {
const instance = expression.compile(val);
return instance({
random: (...args: any[]) => {
Expand All @@ -163,7 +185,7 @@ function EvaluateExpression(val: string) {
/**
* 取不到时返回 undefined
*/
export function getValueFromState(key: string) {
export function legacyGetValueFromState(key: string) {
let ret: any;
const locals = WebGAL.sceneManager.sceneData.currentLocals;
const stage = stageStateManager.getCalculationStageState();
Expand All @@ -187,8 +209,8 @@ export function getValueFromState(key: string) {
/**
* 取不到时返回 {key}
*/
export function getValueFromStateElseKey(key: string, useKeyNameAsReturn = false, quoteString = false) {
const valueFromState = getValueFromState(key);
export function legacyGetValueFromStateElseKey(key: string, useKeyNameAsReturn = false, quoteString = false) {
const valueFromState = legacyGetValueFromState(key);
if (valueFromState === null || valueFromState === undefined) {
logger.warn('valueFromState result null, key = ' + key);
if (useKeyNameAsReturn) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ export const infoFetcher = (url: string): Promise<IGameVar> => {
const appId = String(res);
WebGAL.steam.initialize(appId);
}
if (command === 'Legacy_Expression_Parser') {
WebGAL.legacyExpressionParser = res === true;
}
}
}
});
Expand Down
1 change: 1 addition & 0 deletions packages/webgal/src/Core/webgalCore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,5 @@ export class WebgalCore {
public steam = new SteamIntegration();
public template: WebgalTemplate | null = null;
public styleObjects: Map<string, IWebGALStyleObj> = new Map();
public legacyExpressionParser = false;
}
Loading